Paul Paul - 11 months ago 91
Python Question

Changing list while iterating

I've found a python puzzle and can't find out why it works.

x = ['a','b','c']
for m in x:

and after this loop
x = ['b']
But why?

As far as I understand
keyword implicitly creates iterator for this list. Does
method so
is skipped? I can't find any mentions of it but this is my best guess.

Answer Source

Here you are iterating over the original list. On the first iteration, you removed the 0th index element i.e. a. Now, your list is as: ['b','c']. On the second iteration your for loop will access the value at index 1 but your index 1 has value c. So the c is removed. Hence resultant list will be ['b'].

In order to make it behave expectedly, iterate over the copy of the list, and remove the item from original list. For example:

x = ['a','b','c']
for m in list(x):  # <-- Here 'list(x)' will create the copy of list 'x'
                   # for will iterate over the copy

# update value of 'x' will []

Note: If it is not for demo purpose and you are using this code for emptying the list, efficient way of emptying the list will be:

del x[:]