list IndexError

Fredrik Lundh fredrik at pythonware.com
Wed Dec 22 14:46:23 EST 2004


"Ishwor" <ishwor.gurung at gmail.com> wrote:

> i am trying to remove an item 'e' from the list l but i keep getting IndexError.
> I know the size of the list l is changing in the for loop & its sort
> of trivial task but i found no other way than to suppress the
> IndexError by doing a pass. any other ways you guys can suggest?

this is discussed in the tutorial:

    http://docs.python.org/tut/node6.html#SECTION006200000000000000000

    "It is not safe to modify the sequence being iterated over in the loop
    (this can only happen for mutable sequence types, such as lists). If
    you need to modify the list you are iterating over (for example, to
    duplicate selected items) you must iterate over a copy. The slice
    notation makes this particularly convenient:

    >>> for x in a[:]: # make a slice copy of the entire list
    ...    if len(x) > 6: a.insert(0, x)
    ...
    >>> a
    ['defenestrate', 'cat', 'window', 'defenestrate']

</F> 






More information about the Python-list mailing list