[Tutor] Better structure?

Jacob S. keridee at jayco.net
Thu Feb 3 22:07:04 CET 2005


You can also iterate over a copy of the list and change the original.
i.e.

a = range(10)
for x in a[:]:
    if x % 2 == 0:
        a.remove(x)
print a

And yes, I did test it this time.

Jacob


> 
>> >    for x in string:
>> >        if x in chars:
>> >            string[i] = ''
>>
>> I just have a hangover from other languages, but I really wanted to
> know
>> how Python handles iteration over a variable which is being changed
>> within the loop itself. Is the "for" condition evaluated in every
> loop?
> 
> Its bad practice to delete a member in the collection being iterated
> but Python copes OK if you just change the current item.
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
>


More information about the Tutor mailing list