Quant Metropolis Quant Metropolis - 1 year ago 108
Python Question

Enumerate two python lists simultaneously?

How do I enumerate two lists of equal length simultaneously?
I am sure there must be a more pythonic way to do the following:

for index, value1 in enumerate(data1):
print index, value1 + data2[index]

I want to use the index and data1[index] and data2[index] inside the for loop.

Answer Source

Use zip:

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

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 whole list then use itertools.izip_longest.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download