DEV Community

Cover image for How to Iterate Through Multiple Python Lists at Once
Adrian Perea
Adrian Perea

Posted on • Originally published at adrianperea.dev

How to Iterate Through Multiple Python Lists at Once

The Python zip built-in function makes it easy to iterate through multiple iterables all at once. It aggregates elements from each iterable to create an iterator of tuples. The i-th tuple contains the i-th element of each of the constituent iterables. For example:

>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c']
>>> zipped = zip(x, y)
>>> for x, y in zipped:
...    print(x, y)
...
1 a
2 b 
3 c
Enter fullscreen mode Exit fullscreen mode

Getting the zipped elements as a list

The zip function returns a -- wait for it -- zip object. You can confirm this by printing the zipped variable out in the console. You should see something like this:

>>> zipped = zip(x, y)
<zip object at ox7f45ddba2c08>
Enter fullscreen mode Exit fullscreen mode

To convert it into a list you can manipulate, you use the very aptly named list function like so:

>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]
Enter fullscreen mode Exit fullscreen mode

Unzipping a zip object

If for any reason you need to reverse a zip operation, you can do so with the zip function, in conjunction with the destructuring operator (*) to return the original itertables as tuples:

>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c']
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True 
Enter fullscreen mode Exit fullscreen mode

Zipping unequal list lengths

Zipping unequal list lengths causes the elements of the longer lists to be dropped:

>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c', 'd']
>>> list(zip(x, y))
[(1, 'a'), (2, 'b'), (3, 'c')]
Enter fullscreen mode Exit fullscreen mode

Fortunately, we can use the itertools.zip_longest function to solve this. zip_longest takes iterables as paramaters like zip, but with an additional fillvalue parameter which substitutes for missing values. It defaults to None. Here's how you use it:

>>> from itertools import zip_longest
>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c', 'd']
>>> list(zip_longest(x, y))
[(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd')
Enter fullscreen mode Exit fullscreen mode

And with a fillvalue:

>>> list(zip_longest(x, y, fillvalue=-1))
[(1, 'a'), (2, 'b'), (3, 'c'), (-1, 'd')]
Enter fullscreen mode Exit fullscreen mode

As you can see, with Python, it's very simple to iterate over multiple lists at once.

Further Reading

Top comments (0)