iterating over two sequences at once
Peter Otten
__peter__ at web.de
Sun Jul 25 13:44:24 EDT 2004
Dan wrote:
> This is relatively simple, borrowing from my C++/PHP background:
>
> str = "abcdefg"
> str2 = "abcde"
>
> i = 0
> for c in str:
> print c, " ", str2[i]
> i += 2
>
> But that is a C++/PHP way of doing things.
>
>>From what I've seen of python, I almost expected python to allow:
>
> for c, c2 in str, str2:
>
> But it didn't. I would be very surprised if there isn't another clever
> way of doing the same though.
>>> for c, d in zip("abc", "xyzwillbeignored"):
... print c, d
...
a x
b y
c z
or, if i += 2 isn't there by mistake:
>>> for c, d in zip("abc", "xyzwillbeignored"[::2]):
... print c, d
...
a x
b z
c i
>>>
Using itertools.izip() instead of zip() doesn't create an intermediate list
of tuples which is an advantage when the zip/izip arguments are large
sequences.
> My question to you is, how would you do this? And do you think I should
> propose a PEP for supporting the above for loop syntax? It seems like a
> relatively harmless feature in that it won't break existing code, but
> then I am very new to python.
What you propose already has a meaning and therefore _will_ break existing
code.
>>> for c, d in "ab", "cd":
... print c, d
...
a b
c d
Peter
More information about the Python-list
mailing list