0

I am using python 2.7. I am trying to simulate popping of element from a list using the pop function. But I'm getting an inconsistent result.

Code using a variable list

list_pop = [1,2,3]
for x in list_pop:
    print list_pop
    y = list_pop.pop(0)
    print y

Result:

[1, 2, 3]
1
[2, 3]
2

Code without using variable to hold the list

list_pop = [1,2,3]
for x in [1,2,3]:
    print list_pop
    y = list_pop.pop(0)
    print y

[1, 2, 3]
1
[2, 3]
2
[3]
3
  • I have tried popping index 0 from a list with one element it's working. I'm wondering why my first code halts printing after number 2 but when I print the list_pop it gives [3] the first code should still iterate through it and print 3. I'm expecting same results for both code. What am I missing here?
splucena
  • 383
  • 3
  • 8
  • 17
  • 1
    Your first bit of code should not run. Please copy and paste **exactly** the code you are using for each instance. Additionally, your second bit of code doesn't make sense, as `list_pop` isn't defined. – MattDMo Nov 02 '15 at 01:50

3 Answers3

3

In the first case, you are iterating over the list while modifying it, which will almost certainly give you unexpected results.

In the second case, you are not iterating over the same list you are changing, so the result is a fixed number of iterations.

If you wanted to do the first one and examine all elements, a while loop may work better.

while not len(list_pop) == 0:
    print list_pop
    y = list_pop.pop(0)
    print y

Another alternative is to make a copy of the list and iterate over the copy:

for x in list_pop[:]:
    print list_pop
    y = list_pop.pop(0)
    print y
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • I think the while option is probably a better rule of thumb. If you modify more than one element in the list per loop, iterating over a copy may also result in strange behavior. "while" will always have the desired result: you stop when the list is gone. – subdavis Nov 02 '15 at 02:01
2

A good general rule to follow is that you shouldn't modify a list that you are iterating over. This is exactly the behavior you should get: the list you are iterating over gets smaller and smaller, so the loop will have fewer and fewer items to iterate over. It doesn't iterate over the original list, it iterates over the current list.

In the second example you iterate over a list that never changes, so you get exactly three iterations.

You might want to take a look at this question: Remove items from a list while iterating

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

You should not modify your list while looping through it. That's why the results are inconsistent. Instead you can use a while loop and check is list empty:

while list_pop:
    print list_pop
    y = list_pop.pop(0)
    print y