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.
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.
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.
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.
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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With