I've found a python puzzle and can't find out why it works.
x = ['a','b','c']
for m in x:
x = ['b']
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
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 x.remove(m) # 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: