0

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 []
Conrad Scherb
  • 347
  • 1
  • 3
  • 8

3 Answers3

2

From https://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[:]

Community
  • 1
  • 1
Phu Ngo
  • 666
  • 8
  • 17
0

replace

pop = sortList.pop()

with

pop = sortList[x]

list.pop() deletes the 0th element of the list by unless provided an index such as list.pop(2) etc.

in your case you just have to index not delete the elements from the list.

girish946
  • 705
  • 7
  • 22
0

This is because Python never does copy the objects you pass during a function call. Your list is passed by reference and not by value. So, when you do sortList = li and then sortList.pop() you are actually working on your original myList list (and this is not what you want since you are modifying it with a pop() later).

In order to circumvent that, you need to make a copy of the list, this is exactly what the list() function does.

Try the following code:

def organizeList(_li):
    li = list(_li) # Make an actual copy of the list.
    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
Ryan B.
  • 1,069
  • 9
  • 20