iterating over two sequences at once

Christian Tismer tismer at stackless.com
Sun Jul 25 13:52:37 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.
> 
> 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.

Before iterators and the zip() function were introduced, you had
to either use indexing like this:

for i in range(len(str)):
     c1 = str[i]
     c2 = str2[i]
     ...

or build a list of tuples like so:

for c1, c2 in map(None, str, str2):
     ...

With the zip function, you don't need to understand the map(None... 
construct:

for c1, c2 in zip(str, str2):
     ...

There is a slight difference: map(None... will act on the longest
sequence, augmenting the shorter ones with None, while
zip() will stop when the shortest sequence ends.

A small drawback with the zip() function is that it creates
the whole list of character tuples at once. If you have
larger strings, or you plan to stop the loop early, it
can be more efficient to use izip.
Since Python 2.3, there is also a module named itertools,
which provides you with an iterator voersion of zip().

import itertools
for c1, c2 in itertools.izip(str, str2):
     ...

hope this helps -- ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at stackless.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  mobile +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/




More information about the Python-list mailing list