Skip navigation.

Python - Iterating Multiple Sequences

Python - Iterating Multiple Sequences

Here are some examples of iterating through multiple sequences simultaneously in Python:


I start with 2 lists of numbers:

foos = [0, 1, 2, 3, 4]
bars = [1, 2, 3, 4, 5]

I want to create a new list that is made up of the sum of the items at each position in the original lists.  So I will end up with this:

>>> print foobars

[1, 3, 5, 7, 9]


Starting with an unpythonic way...
Here I use a counter to iterate through the indexes of each sequence and build a new list:

foobars = []
for i in range(len(foos)):
    foo = foos[i]
    bar = bars[i]
    foobars.append(foo + bar)


Getting more pythonic...
Here I use zip. Zip allows me to iterate each sequence simultaneously, assigning the current sequence values each time through the loop:

foobars = []
for foo, bar in zip(foos, bars):
    foobars.append(foo + bar)


The older pythonic way to do this was with map:

foobars = []
for foo, bar in map(None, foos, bars):
    foobars.append(foo + bar)


Getting even more pythonic and more concise...
I can combine zip with a list comprehension and do it in a one-liner like this:

foobars = [foo + bar for (foo, bar) in zip(foos, bars)]


*note:  zip will not be part of Python 3000.  It will be replaced by izip and iterators to achieve similar results.