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
names.append('DDDD')
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)

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try my iOS App