note.nkmk.me

Use enumerate() and zip() at the same time in Python

Posted: 2020-08-27 / Tags: Python

In Python, enumerate() and zip() are useful when iterating elements such as lists in a for loop.

You can get the index with enumerate(), and get the elements of multiple lists together with zip().

The notes when using enumerate() and zip() at the same time are described below.

Sponsored Link

Notes on using enumerate() and zip() at the same time

If you want to get the elements of multiple lists and indexes, you can use enumerate() and zip() at the same time.

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

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)
for i, t in enumerate(zip(names, ages)):
    print(i, t[0], t[1])
# 0 Alice 24
# 1 Bob 50
# 2 Charlie 18
Sponsored Link
Share

Related Categories

Related Posts