Enumerate two python lists simultaneously?
Asked Answered
M

6

109

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.

Merrel answered 1/5, 2013 at 21:29 Comment(0)
R
227

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.

Refrigerant answered 1/5, 2013 at 21:31 Comment(1)
thanks this solved zip(data1, data2).index(val1, val2)Yclept
S
17
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.

Summation answered 1/5, 2013 at 21:31 Comment(9)
Does anyone else hate that enumerate is nine characters long?Endometriosis
@StevenRumbalski: now that you mention it, it could have been named enum to be consistent with len and str.Summation
@jamylak: true, so maybe it should be named enu ;)Summation
@larsmans yeah that would fit in with zip and map! should make a request for Python 4 ;) ;)Slash
@jamylak: don't forget to request rangerng as well to make a stronger case. Oh, and rpr.Summation
@larsmans chain.from_iterablechain.fi and then we should make input() into <> and change print to say (you know to make up for the extra 2 characters I have to type each time I use Py3)Slash
@jamylak: re.match~. Feel like forking Python to start the Pthn prg lng?Summation
@larsmans of course, but I'm afraid that once I start it I won't be able to go back...Slash
@StevenRumbalski: Readability first! - enum() was considered but rejected: PEP 279Merrel
L
11
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

Lust answered 4/7, 2016 at 9:55 Comment(0)
B
2

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
Brantley answered 1/5, 2013 at 21:37 Comment(0)
D
1

Since it has been mentioned that the length are equal,

for l in range(0, len(a)):
   print a[l], b[l]
Dewberry answered 4/7, 2016 at 10:0 Comment(0)
W
-1

Suppose you want to use zip:

   >>> for x in zip([1,2], [3,4]):
    ...     print x
    ... 
    (1, 3)
    (2, 4)
Wimer answered 1/5, 2013 at 21:31 Comment(1)
The index is need inside the loop too.Merrel

© 2022 - 2024 — McMap. All rights reserved.