🎓 A1Learner
🔍

Python Looping Techniques

Looping techniques are small helpers that change how a for loop walks.

Counting the position by hand

Without enumerate(), a separate counter tracks the position.

names = ["Ada", "Bob", "Cy"]
index = 0
for name in names:
    print(index, name)
    index += 1

Index and value with enumerate()

Enumerate pairs each name with its index. The index starts at zero.

names = ["Ada", "Bob", "Cy"]
for index, name in enumerate(names):
    print(index, name)

Two lists together with zip()

Zip pairs the first name with the first score. It then pairs the second name with the second score.

names = ["Ada", "Bob", "Cy"]
scores = [90, 85, 88]
for name, score in zip(names, scores):
    print(name, score)

A first look at dictionary pairs

A dictionary stores labels with values. This is a preview, and dictionaries get a full section later.

points = {"Ada": 90, "Bob": 85}
for name, point in points.items():
    print(name, point)

Walk backwards with reversed()

Reversed walks the list backwards. The list itself stays in its old order.

names = ["Ada", "Bob", "Cy"]
for name in reversed(names):
    print(name)

Example

names = ["Leo", "Sam", "Mia", "Zoe"]
scores = [95, 92, 88, 79]

position = 1
for name, score in zip(names, scores):
    print(position, name, score)
    position += 1

Key points

  • Use enumerate() to get an item and its index together
  • Use zip() to walk two lists side by side, one pair at a time
  • Use items() to get each label and value from a dictionary
  • Use reversed() to walk a list from last to first
  • enumerate(), zip(), items(), and reversed() each give a loop a different walk.

In this example, names and scores hold four entries each. Position starts at 1. Zip pairs each name with the score beside it. The pair prints with its position. Position then grows by one for the next pair. All four pairs print in list order.

Note

zip() stops when the shorter list ends.

Extra items in the longer list are never paired.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which helper gives you an item and its index together?