What is the best way to iterate over multiple lists at once?

Python

Python Problem Overview


Let's say I have two or more lists of same length. What's a good way to iterate through them?

a, b are the lists.

 for i, ele in enumerate(a):
    print ele, b[i]

or

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

or is there any variant I am missing?

Is there any particular advantages of using one over other?

Python Solutions


Solution 1 - Python

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

Solution 2 - Python

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

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
QuestionfrazmanView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonRachel ShallitView Answer on Stackoverflow