I have two iterables, and I want to go over them in pairs:
foo = [1, 2, 3]
bar = [4, 5, 6]
for (f, b) in iterate_together(foo, bar):
print("f:", f, " | b:", b)
That 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 range(len(foo)):
print("f:", foo[i], " | b:", bar[i])
But that seems somewhat unpythonic to me. Is there a better way to do it?
Related tasks:
* How to merge lists into a list of tuples? – given the above foo and bar, create the list [(1, 4), (2, 5), (3, 6)].
* How can I make a dictionary (dict) from separate lists of keys and values? – create the dict {1: 4, 2: 5, 3: 6}.
* Create a dictionary with comprehension – constructing dict using zip in a dict comprehension.
Python 3
zipstops when the shorter offooorbarstops.In Python 3,
zipreturns an iterator of tuples, like
itertools.izipin Python2. To get a listof tuples, use
list(zip(foo, bar)). And to zip until both iterators areexhausted, you would use
itertools.zip_longest.
Python 2
In Python 2,
zipreturns a list of tuples. This is fine when
fooandbarare not massive. If they are both massive then formingzip(foo,bar)is an unnecessarily massivetemporary variable, and should be replaced by
itertools.iziporitertools.izip_longest, which returns an iterator instead of a list.izipstops when eitherfooorbaris exhausted.izip_longeststops when bothfooandbarare exhausted.When the shorter iterator(s) are exhausted,
izip_longestyields a tuple withNonein the position corresponding to that iterator. You can also set a differentfillvaluebesidesNoneif you wish. See here for the full story.Note also that
zipand itszip-like brethen can accept an arbitrary number of iterables as arguments. For example,prints