Iterate over multiple lists (tuple) simultaneously in Python
using zip
When working with data in Python, sometimes we need to iterate over multiple lists simultaneously. One way to do this is by using the built-in zip()
function to create an iterator that aggregates elements from each of the input iterables. In this blog post, we will explore how to use zip()
to iterate over multiple lists in Python.
names = ['A', 'BBB', 'CCCCC']
counts = [len(n) for n in names]
for name, count in zip(names, counts):
print(name, count)
It will stop at the shortest one
using itertools
It 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)
Leave a message
Disclaimer
- Welcome to visit the knowledge base of SRE and DevOps!
- License under CC BY-NC 4.0
- Made with Material for MkDocs and improve writing by generative AI tools
- Copyright issue feedback me#imzye.com, replace # with @