[Tutor] Better structure?

Orri Ganel singingxduck at gmail.com
Thu Feb 3 06:05:24 CET 2005


Sandip Bhattacharya wrote:

>>    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?
>
> - Sandip
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
AFAIK, the for condition in this case *is* evaluated at the beginning of 
every iteration, but this is misleading. For example:

 >>> string=list('banana')
 >>> for x in string:
    string.remove(x)
    print string

Does not print

['a', 'n', 'a', 'n', 'a']
['n', 'a', 'n', 'a']
['a', 'n', 'a']
['n', 'a']
['a']
[]

But rather:

['a', 'n', 'a', 'n', 'a']
['a', 'a', 'n', 'a']
['a', 'a', 'a']

Let's figure this out. First, string is ['b','a','n','a','n','a']. So x 
== 'b'. 'b' is removed, and string printed: ['a', 'n', 'a', 'n', 'a']. 
Then, the for loop grabs the second character in string (which has 
changed) because it has already used the first one. So x == 'n'. 'n' is 
removed and string printed, etc. In general, it is A Good Idea to not 
change the length of sequences as you loop over them.  If you use a for 
i in range(len(string)): style, you will get an IndexError because in 
this case Python does *not* check len(string) every iteration. If you 
use a different style, you will just get weird results.

HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list