[Tutor] basic lists and loops question

Kent Johnson kent37 at tds.net
Thu May 15 03:30:58 CEST 2008


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


More information about the Tutor mailing list