Enumerate two python lists simultaneously?

PythonList

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

Althought this is not very clear what you look for,

>>> data1 = [3,4,5,7]
>>> data2 = [4,6,8,9]
>>> for index, value in enumerate(zip(data1, data2)):
	print index, value[0]+value[1]

	
0 7
1 10
2 13
3 16

Solution 5 - Python

Since it has been mentioned that the length are equal,

for l in range(0, len(a)):
   print a[l], b[l]

Solution 6 - Python

Suppose you want to use zip:

   >>> for x in zip([1,2], [3,4]):
    ...     print x
    ... 
    (1, 3)
    (2, 4)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuant MetropolisView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonFred FooView Answer on Stackoverflow
Solution 3 - PythonMarco SullaView Answer on Stackoverflow
Solution 4 - PythonkiriloffView Answer on Stackoverflow
Solution 5 - PythonSuperNovaView Answer on Stackoverflow
Solution 6 - PythonddzialakView Answer on Stackoverflow