[Tutor] Help understanding list comprehensions

Alan Gauld alan.gauld at btinternet.com
Thu Jun 18 10:20:44 CEST 2015


On 18/06/15 05:40, Anubhav Yadav wrote:
> So I need to create a copy of the list before trying to iterate through the
> list.

Only if you are going to change it.
The problem you had was that you were removing items
from the thing you were iterating over. As a result
the other items effectively moved up one place to fill
the gap resulting in you stepping over some items without
processing them.

Similarly problems can ensue if you insert new items
into a list while iterating over it. You may wind up
processing some items twice while not processing the
new items you added. It's just a bad idea to modify
the structure of the thing you are iterating over.

So, if you intend modifying the list structure make a
copy. Otherwise you can iterate over the original list
(or dictionary, or whatever) without problems.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list