Sentry Answers>Python>

Accessing the Index in a `for` Loop in Python

Accessing the Index in a `for` Loop in Python

Naveera A.

The Problem

How can you access the index of each element while using Python’s for loop?

Let’s say we have the following list:

Click to Copy
directions = ['north', 'east', 'south', 'west']

Usually, we don’t need the indexes of the elements. So Python provides a simpler method of looping where instead of retrieving item indexes and looking up each element, we can just loop over the elements directly, like so:

Click to Copy
directions = ['north', 'east', 'south', 'west'] for direction in directions: print(direction)

But what if we need the indexes? For example, if we want the following output where each element is printed alongside its index in the list:

Click to Copy
0 north 1 east 2 south 3 west

The Solution

Python’s for loops are actually foreach loops. A foreach loop makes the code simpler to read but it maintains no counters. So rather than saying “do this n times”, a foreach loop essentially says “do this to everything in the sequence”.

For scenarios where we actually need the index or counter variable, we can use Python’s built-in enumerate function. The enumerate function returns an iterable. Each element of this iterable is a tuple containing the index of the item and the original item value, like so:

Click to Copy
directions = ['north', 'east', 'south', 'west'] directions_tuples = enumerate(directions) # output [(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]

We can unpack the tuple in two variables and use it in the for loop, like so:

Click to Copy
directions = ['north', 'east', 'south', 'west'] for index, direction in enumerate(directions): print(f"{index} {direction}")

This will print the following output:

Click to Copy
0 north 1 east 2 south 3 west

The enumerate function also takes an optional argument, start. We can use this argument to change the starting index. By default, the value of start is 0.

Let’s say we want to print the directions with a natural counting number, we can set the value of start to 1, like so:

Click to Copy
directions = ['north', 'east', 'south', 'west'] for index, direction in enumerate(directions, start=1): print(f"{index} {direction}")

This time we will get the following output:

Click to Copy
1 north 2 east 3 south 4 west

There are other ways of accessing index or counter variables, for example using the range and len functions, like so:

Click to Copy
for index in range(len(directions)): print(f"{index} {directions[index]}")

But using the enumerate function is the recommended and pythonic way of achieving this result.

  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Syntax.fmListen to the Syntax Podcast
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.