Loop Patterns: enumerate, zip, and Nesting

Python 3.12 · ✓ verified by execution on 2026-07-23

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

python
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
Output
0 tic
1 tac
2 toe

Using Enumerate with a Start Index

python
for i, v in enumerate(['first', 'second'], start=1):
    print(f'Place {i}: {v}')
Output
Place 1: first
Place 2: second

The Zip Function

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

python
questions = ['name', 'color']
answers = ['lancelot', 'blue']
for q, a in zip(questions, answers):
    print(q, a)
Output
name lancelot
color blue

Zip with Unequal Lengths

zip() stops when the shortest iterable is exhausted.

python
a = [1, 2, 3]
b = ['w', 'x']
for num, letter in zip(a, b):
    print(num, letter)
Output
1 w
2 x

The Accumulator Pattern

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

python
raw_data = [56.2, 51.7, 55.3, 52.5, 47.8]
filtered_data = []
for value in raw_data:
    if value > 50:
        filtered_data.append(value)
print(filtered_data)
Output
[56.2, 51.7, 55.3, 52.5]

Nested Loops

Python’s for statement iterates over the items of any sequence

python · visualize
for i in range(1, 3):
    for j in ['a', 'b']:
        print(f'{i}{j}')

Check yourself

You need to keep track of an index variable manually (e.g., i = 0) to know where you are in a list.

Reveal answer

Python provides enumerate() specifically to handle indices cleanly and pythonically. — Python provides enumerate() specifically to handle indices cleanly and pythonically.

zip() will crash if the lists are different lengths.

Reveal answer

zip() silently truncates to the shortest list (unless you use itertools.zip_longest or strict=True in 3.10+). — zip() silently truncates to the shortest list (unless you use itertools.zip_longest or strict=True in 3.10+).

Removing items from a list while iterating over it is safe.

Reveal answer

Modifying a list while iterating over it shifts elements and skips items. It is safer to build a new list. — Modifying a list while iterating over it shifts elements and skips items. It is safer to build a new list.

In a nested loop, the inner loop continues from where it left off.

Reveal answer

The inner loop restarts completely from its first element for every single iteration of the outer loop. — The inner loop restarts completely from its first element for every single iteration of the outer loop.

Challenges

Challenge 1 +15 XP

Write a function 'format_ranking' that takes a list of names and returns a list of strings formatted as '1. Name', '2. Name', etc.

python
  • Test 1 — expects "['1. Alice', '2. Bob', '3. Charlie'] \n"
Need a hint? (−25% XP)

Use enumerate() with the start=1 argument to get the position, and use an accumulator pattern or list comprehension to build the result.

Show solution (0 XP)
def format_ranking(names):
    return [f'{i}. {name}' for i, name in enumerate(names, start=1)]
print(format_ranking(['Alice', 'Bob', 'Charlie']))

Challenge 2 +15 XP

Write a function 'combine_scores' that takes a list of student names and a list of their scores, returning a dictionary mapping names to scores.

python
  • Test 1 — expects "{'Alice': 85, 'Bob': 92} \n"
Need a hint? (−25% XP)

Use zip() to pair up the names and scores, and add them to a dictionary accumulator.

Show solution (0 XP)
def combine_scores(names, scores):
    result = {}
    for name, score in zip(names, scores):
        result[name] = score
    return result
print(combine_scores(['Alice', 'Bob'], [85, 92]))