Modifying a list while looping through it
asmeurer opened this issue · 1 comments
A nice addition to your "not so obvious" notebook would be the modifying a list while looping through it pitfall. For instance, you might be tempted into believing that the following will remove all even values from the list a
>>> a = [1, 2, 3, 4, 5]
>>> for i in a:
... if not i % 2:
... a.remove(i)
...
>>> a
[1, 3, 5]
But if you try a different example:
>>> a = [2, 4, 5, 6]
>>> for i in a:
... if not i % 2:
... a.remove(i)
...
>>> a
[4, 5]
I'll leave it as an exercise for you to figure out exactly what is going on here.
Dictionaries will protect you from this by raising an exception if they change during iteration, but for lists, you should use a copy (for i in a[:]
), or convert the for
loop into a while
loop.
Great notebook by the way!
Thanks, Aaron, this is a really really great one. I really love it! Never screw with the indexing ;)
I added a section http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/not_so_obvious_python_stuff.ipynb?create=1#looping_pitfall