Skip to content

Iterate over multiple lists (tuple) simultaneously in Python

using zip

will stop at the shortest one

names = ['A', 'BBB', 'CCCCC']
counts = [len(n) for n in names]
for name, count in zip(names, counts):
    print(name, count)

using itertools

will stop at the longest one

import itertools
for name, count in itertools.zip_longest(names, counts):
    print(f'{name}: {count}')

fill the default value

import itertools 

num = [1, 2, 3]
color = ['red', 'while', 'black']
value = [255, 256]

for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue=-1):
    print(a, b, c)