Enumerate two python lists simultaneously?

Use zip for both Python2 and Python3:

for index, (value1, value2) in enumerate(zip(data1, data2)):
    print(index, value1 + value2)  # for Python 2 use: `print index, value1 + value2` (no braces)

Note that zip runs only up to the shorter of the two lists(not a problem for equal length lists), but, in case of unequal length lists if you want to traverse the whole list then use itertools.izip_longest.


for i, (x, y) in enumerate(zip(data1, data2)):

In Python 2.x, you might want to use itertools.izip instead of zip, esp. for very long lists.


from itertools import count

for index, value1, value2 in zip(count(), data1, data2):
    print(index, value1, value2)

Source: http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/#c2603

Tags:

Python

List