How to iterate through two lists in parallel? How to iterate through two lists in parallel? python python

How to iterate through two lists in parallel?


Python 3

for f, b in zip(foo, bar):    print(f, b)

zip stops when the shorter of foo or bar stops.

In Python 3, zipreturns an iterator of tuples, like itertools.izip in Python2. To get a listof tuples, use list(zip(foo, bar)). And to zip until both iterators areexhausted, you would useitertools.zip_longest.

Python 2

In Python 2, zipreturns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massivetemporary variable, and should be replaced by itertools.izip oritertools.izip_longest, which returns an iterator instead of a list.

import itertoolsfor 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 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.


Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],                               ['red', 'blue', 'green']):    print('{} {} {}'.format(num, color, cheese))

prints

1 red manchego2 blue stilton3 green brie


You want the zip function.

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


You should use 'zip' function. Here is an example how your own zip function can look like

def custom_zip(seq1, seq2):    it1 = iter(seq1)    it2 = iter(seq2)    while True:        yield next(it1), next(it2)