iterating over two sequences at once
Pierre-Frédéric Caillaud
peufeu at free.fr
Sun Jul 25 15:19:28 EDT 2004
> for c, c2 in a, b:
This is a valid syntax but it does not do I think you think it does :
It will iterate over the list (in fact tuple) (a, b), so the loop will
run two times, just as if you had typed "for c, c2 in (a, b):".
At each iteration it will try to put the item in (c,c2), so if a and b
are 2-item tuples, say :
a= ("g",5) and b=("f",6)
you'll have :
first iteration :
c = "g" and c2=5
second iteration :
c = "f" and c2=6
got it ?
For can only manage one iterable (i'ts a one-level loop) so you'll either
need to use indices :
for pos, letter in enumerate(str1):
letter2 = str2[letter*2]
...
Or you can use zip to join your two iterables in one :
for letter1, letter2 in zip( str1, str2[::2]):
...
I'm not sure about the slice syntax [::2] but it means "every other
char", chekc the docs.
More information about the Python-list
mailing list