Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modifying a list while looping through it #2

Closed
asmeurer opened this issue Apr 17, 2014 · 1 comment
Closed

Modifying a list while looping through it #2

asmeurer opened this issue Apr 17, 2014 · 1 comment

Comments

@asmeurer
Copy link

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!

@rasbt
Copy link
Owner

rasbt commented Apr 17, 2014

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

@rasbt rasbt closed this as completed Apr 17, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants