Conventions for iterators

Jeff Shannon jeff at ccvcorp.com
Fri Feb 1 14:12:50 EST 2002


jlbec at evilplan.org wrote:

> With "one modification invalidates
> the iterator," you cannot have code like:
>
> for item in list:
>     if matches(item):
>         list.remove(item)

Note that Python's current (non-iterator) behavior does not behave well in
this sort of situation, either.

PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com)
>>> mylist = range(10)
>>> for i in mylist:
...  print i
...  mylist.remove(i)
...
0
2
4
6
8
>>>

As Tim Peters has pointed out, any time you mutate the object that you're
iterating over, you're asking for weirdness.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list