Conrad Scherb Conrad Scherb - 3 months ago 9
Python Question

List emptied after a function

I have a function in a program which requires me to organise a list in a specific order, however MyList is emptied after the function resolves? What is wrong with my function and how do I fix it?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def organizeList(li):
finalList = []
sortList = li
sortList.sort()
for x in range(len(li)):
pop = sortList.pop()
if len(finalList) % 2 == 0:
finalList.append(pop)
else:
finalList.insert(0, pop)
return finalList

print(myList) # Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(organizeList(myList)) # Returns [1, 3, 5, 7, 9, 10, 8, 6, 4, 2]
print(myList) # Returns []

Answer

From http://stackoverflow.com/a/986145/1400623:

the parameter passed in is actually a reference to an object

Your sortList, li and myList point to the same object that gets emptied by sortList.pop() Fix this by cloning/copying instead, for example: sortList=li[:]

Comments