Re: iterating over two sequences at once

From: Peter Otten (__peter___at_web.de)
Date: 07/25/04


Date: Sun, 25 Jul 2004 19:44:24 +0200

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



Relevant Pages

  • Re: Collapsible wheel
    ... Dan ... Very clever, but I fear that except for the special case of wheelchairs, ...
    (rec.bicycles.tech)
  • Re: Open form from switchboard and assign recordsource from selection
    ... Dan, I attempted to answer your original post you sent on the 19th. ... > problem with assigning the str. ... > names of the buttons, option1, option2, etc and the name ...
    (microsoft.public.access.forms)
  • Re: Collapsible wheel
    ... Dan ... Very clever, but I fear that except for the special case of wheelchairs, they are overestimating the downside to small wheels. ...
    (rec.bicycles.tech)
  • Re: Refer to the first row of the table
    ... clever, gives me a syntax error and i must have written something ... You've left off one of the parentheses I had in my original SQL ... don't name your function "str". ...
    (microsoft.public.access.modulesdaovba)
  • Re: Collapsible wheel
    ... Dan ... Very clever, but I fear that except for the special case of wheelchairs, ...
    (rec.bicycles.tech)