Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate two python lists simultaneously?

Tags:

python

list

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.

like image 419
Quant Metropolis Avatar asked May 01 '13 21:05

Quant Metropolis


People also ask

How do you enumerate two lists in Python?

If you want to get the elements of multiple lists and indexes, you can use enumerate() and zip() together. In this case, you need to enclose the elements of zip() in parentheses, like for i, (a, b, ...) in enumerate(zip( ... )) . You can also receive the elements of zip() as a tuple.

Can you iterate through two lists simultaneously Python?

We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.

Can you use enumerate with a list in Python?

Enumerate() in Python Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.

Does enumerate work with lists?

The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary. In addition, it can also take in an optional argument, start, which specifies the number we want the count to start at (the default is 0). And that's it!


1 Answers

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.

like image 165
Ashwini Chaudhary Avatar answered Oct 24 '22 20:10

Ashwini Chaudhary