-1

It appears that when I want to remove an item from a list, the order gets shuffled. I currently have the following code:

todo = []
for case in cases:
    todo.append(case)

for case in todo:
    print(case[1]) #first print

while(len(todo) > 0):
    for case in todo:
        subject = case[1]
        print("Case: " + str(subject)) #second print
        todo.remove(case)

This gives the following result (first print):

55566 
66977
66977
136566
136566
37493
37493
37493
63126
37289

And then the second print (in a different order):

Case: 55566
Case: 66977 
Case: 136566
Case: 37493
Case: 63126
Case: 66977
Case: 37493
Case: 37289
Case: 136566
Case: 37493

Does remove imply sorting? And if so, how to maintain the order?

Bas
  • 1,232
  • 1
  • 12
  • 26

1 Answers1

4

.remove() is certainly not sorting your list. Rather, you are just ruining your iteration over the list by removing elements within it. Essentially, when you remove a case from todo during iteration, all of the remaining cases in todo are slid down your list by one place. Then your iteration misses an index, and you get undesired results. The lesson to be learned is do not remove elements from a list while you are iterating over it. An alternative could be a list comprehension, or going backwards.

This undesired behavior can be more easily understood by seeing that these two loops are equivalent, with the second simply being a lower-level representation

cases = [1,2,3]
for case in cases:
    print(case)
    cases.remove(case)

i = 0
while i < len(cases):
    x = cases[i]
    print(x)
    cases.remove(x)
    i+=1
Community
  • 1
  • 1
miradulo
  • 28,857
  • 6
  • 80
  • 93
  • Alright, thanks for the explanation. Makes sense with the indexing and how the list is updated after a remove :) – Bas May 17 '16 at 15:05