Python enumerate(): Simplify Looping With Counters

Python enumerate(): Simplify Loops That Need Counters

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Looping With Python enumerate()

In Python, a for loop is usually written as a loop over an iterable object. This means you don’t need a counting variable to access items in the iterable. Sometimes, though, you do want to have a variable that changes on each loop iteration. Rather than creating and incrementing a variable yourself, you can use Python’s enumerate() to get a counter and the value from the iterable at the same time!

In this tutorial, you’ll see how to:

  • Use enumerate() to get a counter in a loop
  • Apply enumerate() to display item counts
  • Use enumerate() with conditional statements
  • Implement your own equivalent function to enumerate()
  • Unpack values returned by enumerate()

Let’s get started!

Iterating With for Loops in Python

A for loop in Python uses collection-based iteration. This means that Python assigns the next item from an iterable to the loop variable on every iteration, like in this example:

>>>
>>> values = ["a", "b", "c"]

>>> for value in values:
...     print(value)
...
a
b
c

In this example, values is a list with three strings, "a", "b", and "c". In Python, lists are one type of iterable object. In the for loop, the loop variable is value. On each iteration of the loop, value is set to the next item from values.

Next, you print value onto the screen. The advantage of collection-based iteration is that it helps avoid the off-by-one error that is common in other programming languages.

Now imagine that, in addition to the value itself, you want to print the index of the item in the list to the screen on every iteration. One way to approach this task is to create a variable to store the index and update it on each iteration:

>>>
>>> index = 0

>>>