Site icon Machine Learning Projects

Python Program to Iterate Through Two Lists in Parallel – 2023

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Iterate Through Two Lists in Parallel.

Example 1: Using zip (Python 3+)

# Python Program to Iterate Through Two Lists in Parallel

list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3, 4]

for i, j in zip(list_1, list_2):
    print(i, j)

Output

a 1
b 2
c 3

Example 2: Using itertools (Python 2+)

import itertools

list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3, 4]

# loop until the short loop stops
for i,j in zip(list_1,list_2):
    print(i,j)

print("\n")

# loop until the longer list stops
for i,j in itertools.zip_longest(list_1,list_2):
    print(i,j)

Output

a 1
b 2
c 3


a 1
b 2
c 3
None 4

Check out our other python programming examples

Exit mobile version