so im trying to implement selection sort in python.. and im appending the result of each iteration to a list to print at the end.. my code sorts the list of numbers properly but
Your code doesn't actually do what you say it does. In fact, it doesn't even run. But here's a simple example that does demonstrate the problem you're seeing:
def s_sort(numbers):
alist=[]
alist.append(numbers)
numbers.sort()
alist.append(numbers)
return alist
The problem is that alist
is not a list of two different lists, it's a list of the same list twice in a row. So, when you modify that one list, of course that one list is modified everywhere it appears—in numbers
, and in alist[0]
, and in alist[1]
.
The solution is to not add the same list multiple times; instead, add a new one. For example:
def s_sort(numbers):
alist=[]
alist.append(numbers[:])
alist.append(sorted(numbers))
return alist
Now you've created two brand-new lists—one an exact copy of the original, one a sorted copy—and returned a list of them.
So, instead of returning [[3, 5, 7], [3, 5, 7]]
(and also changing numbers
to be [3, 5, 7]
), it returns [[5, 7, 3], [3, 5, 7]]
(and leaves numbers
alone).
I have no idea why you expected [3, 7, 5]
for the first element, but maybe you're doing some other work to the first element of alist
which you didn't show us. In which case, as long as you do that work in a copying rather than mutating way (ala sorted(n)
vs. n.sort()
) or do it to a copy, everything will be fine.