Use enumerate() and zip() Together in Python
In Python, enumerate()
and zip()
are useful when iterating over elements of iterable (list
, tuple
, etc.) in a for
loop.
You can get the index with enumerate()
, and get the elements of multiple iterables with zip()
.
This article describes the notes when using enumerate()
and zip()
together.
Notes on using enumerate()
and zip()
together
To get elements and indices from multiple lists simultaneously, you can combine enumerate()
and zip()
.
In this case, you need to enclose the elements of zip()
in parentheses, like for i, (a, b, ...) in enumerate(zip( ... ))
.
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for i, (name, age) in enumerate(zip(names, ages)):
print(i, name, age)
# 0 Alice 24
# 1 Bob 50
# 2 Charlie 18
source: for_enumerate_zip.py
You can also receive the elements of zip()
as a tuple.
for i, t in enumerate(zip(names, ages)):
print(i, t)
# 0 ('Alice', 24)
# 1 ('Bob', 50)
# 2 ('Charlie', 18)
source: for_enumerate_zip.py
for i, t in enumerate(zip(names, ages)):
print(i, t[0], t[1])
# 0 Alice 24
# 1 Bob 50
# 2 Charlie 18
source: for_enumerate_zip.py
Note that you can use itertools.count()
and zip()
functions to create a non-nested form like (i, a, b)
.