Python20 min read
Python Enumerate and Zip
Learn enumerate and zip to write clean loops, avoid index bugs, and combine multiple sequences safely.
Michael Brown
July 22, 2025
13.1k314
When looping in Python, beginners often write complex loops using indexes. Python gives you tools to make loops cleaner and safer.
Two such tools are:
- enumerate() → index + value
- zip() → combine multiple iterables
## enumerate(): index with value
```python
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
```
Expected output:
```
0 apple
1 banana
2 orange
```
Start from custom number:
```python
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
```
## Why enumerate is better
Instead of:
```python
for i in range(len(fruits)):
print(i, fruits[i])
```
Use:
```python
for i, fruit in enumerate(fruits):
print(i, fruit)
```
Cleaner and safer.
## zip(): combine sequences
```python
names = ["Tom", "Sarah", "Mike"]
ages = [25, 28, 30]
for name, age in zip(names, ages):
print(name, age)
```
zip stops at the shortest list.
## zip into dictionary
```python
keys = ["name", "age", "city"]
values = ["Tom", 25, "Austin"]
person = dict(zip(keys, values))
print(person)
```
## Unzip values
```python
pairs = [(1, "a"), (2, "b"), (3, "c")]
nums, letters = zip(*pairs)
print(nums)
print(letters)
```
## Practical example: leaderboard
```python
students = ["Tom", "Sarah", "Mike"]
scores = [85, 92, 78]
leaderboard = list(zip(students, scores))
leaderboard.sort(key=lambda x: x[1], reverse=True)
for rank, (name, score) in enumerate(leaderboard, start=1):
print(f"{rank}. {name}: {score}")
```
## Graph: enumerate vs zip
```mermaid
flowchart LR
A[List] --> B[enumerate]
B --> C[Index + Value]
D[List 1] --> E[zip]
F[List 2] --> E
E --> G[Paired Values]
```
## Key points
- enumerate for index + value
- zip to combine iterables
- Makes loops readable and bug-free
In the next lesson, you will explore map, filter, and reduce, which introduce functional-style data processing.
#Python#Intermediate#Loops