views:

526

answers:

4

Possible Duplicates:
Iterate a list as tuples in python
How do I iterate over the tuples of the items of two or more lists in Python?

I have two iterables in Python and I want to go over them in pairs:

foo = (1,2,3)
bar = (4,5,6)

for (f,b) in some_iterator(foo, bar):
    print "f: ", f ,"; b: ", b

should result in:

f: 1; b: 4
f: 2; b: 5
f: 3; b: 6

One way to do it is to iterate over the indeces:

for i in xrange(len(foo)):
    print "f: ",foo[i] ,"; b: ", b[i]

But that seems somewhat unpythonic to me. Is there a better way to do it?

+4  A: 

You want the zip function.

for (f,b) in zip(foo, bar):
    print "f: ", f ,"; b: ", b
Karl Guertin
Before Python 3.0 you'd want to use `itertools.izip` if you have large numbers of elements.
Georg
+2  A: 

What you're looking for is called zip.

Alex Martelli
+4  A: 

The builtin zip does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.

thrope
+9  A: 
for f,b in zip(foo,bar):
    print(f,b)

zip returns a tuple. zip stops when the shorter of foo or bar stops. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by izip or izip_longest, which returns an iterator instead of a tuple.

from itertools import izip,izip_longest
for f,b in izip(foo,bar):
    print(f,b)
for f,b in izip_longest(foo,bar):
    print(f,b)

izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.

unutbu