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
It 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 indices:
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?
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.What you're looking for is called
zip
.zip
stops when the shorter offoo
orbar
stops.In Python 2,
zip
returns a list of tuples. This is fine whenfoo
andbar
are not massive. If they are both massive then formingzip(foo,bar)
is an unnecessarily massive temporary variable, and should be replaced byitertools.izip
oritertools.izip_longest
, which returns an iterator instead of a list.izip
stops when eitherfoo
orbar
is exhausted.izip_longest
stops when bothfoo
andbar
are exhausted. When the shorter iterator(s) are exhausted,izip_longest
yields a tuple withNone
in the position corresponding to that iterator. You can also set a differentfillvalue
besidesNone
if you wish. See here for the full story.In Python 3,
zip
returns an iterator of tuples, likeitertools.izip
in Python2. To get a list of tuples, uselist(zip(foo, bar))
. And to zip until both iterators are exhausted, you would use itertools.zip_longest.Note also that
zip
and itszip
-like brethen can accept an arbitrary number of iterables as arguments. For example,prints
You should use 'zip' function. Here is an example how your own zip function can look like
You want the
zip
function.