the full guide

enumerate and zip

enumerate() gives the position and the value together as you loop over a sequence. zip() walks through two or more sequences side by side, pairing up their items.

5 min Intermediate

What you need: The earlier topics of this module.

Definition

enumerate() gives the position and the value together as you loop over a sequence. zip() walks through two or more sequences side by side, pairing up their items.

In simple words

enumerate is roll numbers: 1 Riya, 2 Aman. zip is matching a list of names with a list of marks, the first with the first, and the second with the second.

Why it matters

They replace clumsy range(len(x)) loops, so code gets shorter and has fewer bugs. You'll see them constantly in data work.

How it works

In code

loops.py
names = ["Riya", "Aman", "Sara"]
marks = [91, 78, 85]

for number, name in enumerate(names, start=1):
    print(number, name)

for name, mark in zip(names, marks):
    print(name, "scored", mark)

print(dict(zip(names, marks)))
print(list(zip([1, 2, 3], ["a", "b"])))

Output

1 Riya
2 Aman
3 Sara
Riya scored 91
Aman scored 78
Sara scored 85
{'Riya': 91, 'Aman': 78, 'Sara': 85}
[(1, 'a'), (2, 'b')]

Common mistakes

  • Writing for i in range(len(names)) when you only need the items.
  • Not noticing that zip dropped items because lengths differed.

Check yourself

Question 1

1. What does list(zip([1, 2], [3, 4, 5])) give?

Question 2

2. How do you start enumerate at 1?

Summary

  • enumerate gives position and value.
  • zip pairs sequences, and stops at the shortest.

Finished reading?

Sources: The Python Tutorial, python.org