Python - Iterating Multiple Sequences
Python - Iterating Multiple Sequences
Submitted by Corey Goldberg on Sat, 10/03/2007 - 21:14.Here are some examples of iterating through multiple sequences simultaneously in Python:
I start with 2 lists of numbers:
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:
[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:
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:
for foo, bar in zip(foos, bars):
foobars.append(foo + bar)
The older pythonic way to do this was with map:
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:
*note: zip will not be part of Python 3000. It will be replaced by izip and iterators to achieve similar results.
