How can I iterate through two lists in parallel in Python?

PythonServer Side ProgrammingProgramming

Assuming that two lists may be of unequal length, parallel traversal over common indices can be done using for loop over over range of minimum length

>>> L1
['a', 'b', 'c', 'd']
>>> L2
[4, 5, 6]
>>> l=len(L1) if len(L1)<=len(L2)else len(L2)
>>> l
>>> for i in range(l):
    print (L1[i], L2[i])

a 4
b 5
c 6

A more pythonic way is to use zip() function which results in an iterator that aggregates elements from each iterables

>>> for i,j in zip(L1,L2):
    print (i,j)

a 4
b 5
c 6

Published on 30-Jan-2018 00:09:56