Here are some examples of iterating through multiple sequences simultaneously in Python:
I start with 2 lists of numbers:
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:
Starting with an unpythonic way... Here I use a counter to iterate through the indexes of each sequence and build a new list:
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:
The older pythonic way to do this was with map:
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.
Copyright © 2006-2008 Corey Goldberg
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.