string issue

Fredrik Lundh fredrik at pythonware.com
Fri Feb 4 14:54:03 EST 2005


"rbt" <rbt at athop1.ath.vt.edu> wrote:

>> You are modifying the list as you iterate over it. Instead, iterate over a copy by using:
>>
>> for ip in ips[:]:
>>   ...
>>
>> regards
>>  Steve
>
> Very neat. That's a trick that everyone should know about.

I suppose that's why it's included in the Python 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)

(slice notation is explained in an earlier chapter)

</F> 






More information about the Python-list mailing list