Kent Johnson | 15 May 03:30
Gravatar

Re: basic lists and loops question

On Wed, May 14, 2008 at 9:06 PM, Kent Johnson <kent37 <at> tds.net> wrote:

>> I understand about removing elements from a container you're iterating. Is
>> data.remove(x) problematic in this context?
>
> Yes. It can cause the iteration to skip elements of the list.

For example:
In [1]: l=range(5)
In [2]: for i in l:
   ...:     print i
   ...:     if i==2:
   ...:         l.remove(i)
   ...:
   ...:
0
1
2
4

Notice how 3 is skipped. Don't do this!

Kent
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor


Gmane