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
f: 1; b: 4
f: 2; b: 5
f: 3; b: 6
for i in xrange(len(foo)):
print "f: ", foo[i], "; b: ", b[i]
for f, b in zip(foo, bar): print(f, b)
zip stops when the shorter of
In Python 2,
zip returns a list of tuples. This is fine when
bar are not massive. If they are both massive then forming
an unnecessarily massive temporary variable, and should be replaced by
itertools.izip_longest, which returns an iterator instead
of a list.
import itertools for f,b in itertools.izip(foo,bar): print(f,b) for f,b in itertools.izip_longest(foo,bar): print(f,b)
izip stops when either
bar is exhausted.
izip_longest stops when both
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
None if you wish. See here for the full story.
In Python 3,
zip returns an iterator of tuples, like
itertools.izip in Python2.
To get a list of tuples, use
list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.