Software, Tech & Coding simplified.

Python For Loop with Index: Access the Index in a For Loop

To access the index in a for loop in Python, use the enumerate() function.

For example:

names = ["Alice", "Bob", "Charlie"]

for position, name in enumerate(names):
    print(f"{name}: {position}")

Output:

Alice: 0
Bob: 1
Charlie: 2

This is a quick answer to your question.

However, if you are unfamiliar with the syntax, or want to figure out alternative ways to access the index in a for loop, please stick around.

In this guide you learn how to:

  • Use the enumerate() function to get a for loop index.
  • How to start loop index at 1 or some other value than 0.
  • Alternative ways to perform a for loop with index, such as:
    • Update an index variable
    • List comprehension
    • The zip() function
    • The range() function

The enumerate() Function in Python

The most elegant way to access the index of for loop in Python is by using the built-in enumerate() function.

Before seeing a bunch of examples, let’s take a look at how the enumerate() function works.

How Does the enumerate() Function Work

The enumerate() function can be called on any iterable in Python.

It then couples each element in the iterable with an index and returns the result as an enumerate object.

To visualize the enumerate object, you can convert it to a list using the list() function.

For example:

names = ["Alice", "Bob", "Charlie"]
names_idx = enumerate(names)

print(list(names_idx))

Output:

[(0, 'Alice'), (1, 'Bob'), (2, 'Charlie')]

As you can see, the names in the list are now inside a tuple and for each name, there is a related index.

Here is an illustration of the enumeration process:

Python enumerate function couples elements with index
The enumerate function couples each element with an index.

When you call enumerate() the indexing starts at 0 by default.

However, you can change this by specifying an optional start parameter to the enumerate() function call.

For instance, let’s make indexing start at 1:

names = ["Alice", "Bob", "Charlie"]
names_idx = enumerate(names, start=1)

print(list(names_idx))

Output:

[(1, 'Alice'), (2, 'Bob'), (3, 'Charlie')]

Now that you understand how the enumerate() function works, let’s use it to access the index in a for loop.

How to Get the Index in For Loop

To get the index in a for loop:

  1. Call the enumerate() function on the iterable.
  2. Access the index, element pairs using a forin loop.

For example:

names = ["Alice", "Bob", "Charlie"]
names_idx = enumerate(names)

for index, name in names_idx:
    print(f"{name}: {index}")

Output:

Alice: 0
Bob: 1
Charlie: 2

If you are a beginner and have a hard time understanding the index, name part in the loop, please check the tuple unpacking article.

By the way, you do not need to separately store the enumerated iterable into a separate variable. Instead, you can call the enumerate() function directly when starting the for loop.

This saves you a line of code.

For instance:

names = ["Alice", "Bob", "Charlie"]

for index, name in enumerate(names):
    print(f"{name}: {index}")

Output:

Alice: 0
Bob: 1
Charlie: 2

Next, let’s take a look at how to change the index at which the enumeration starts.

How to Start Indexing at a Custom Value

In the previous example, the indexing starts at 0.

However, it is quite common you want the indexing to start from somewhere else than 0.

Luckily, the enumerate() function makes it possible to specify a non-zero starting index.

To for loop with index other than 0:

  1. Call the enumerate() function on the iterable and specify the start parameter.
  2. Access the index, element pairs using a forin loop.

For example, let’s make indexing start at 1:

names = ["Alice", "Bob", "Charlie"]

for index, name in enumerate(names, start=1):
    print(f"{name}: {index}")

Output:

Alice: 1
Bob: 2
Charlie: 3

Enumerate Works with All Iterables

So far you have only seen how to access for loop index when dealing with lists in Python.

However, you can call the enumerate() function on any iterable type in Python, such as a tuple or string.

By the way, if you are unfamiliar with iterables, please check this complete guide.

For example, let’s get the indices of each letter in a string:

word = "Hello"

for pos, letter in enumerate(word):
    print(f"{letter}: {pos}")

Output:

H: 0
e: 1
l: 2
l: 3
o: 4

Now you understand how to use the enumerate() function to get the index of a for loop in Python.

This is such an elegant solution to the problem. I recommend you stick with it.

However, for the sake of completeness, I am going to show alternative ways to index for loops.

Alternative Ways to For Loops with Index

Here is a list of alternative ways to access the for loop index in Python.

Separate Index Variable

The most basic way to get the index of a for loop is by keeping track of an index variable.

This is commonly taught in beginner-level programming courses. Also, some programming languages do not even have a function like enumerate() you could use.

For instance, let’s print the names and their position in a list:

names = ["Alice", "Bob", "Charlie"]

index = 0
for name in names:
    print(f"{name}: {index}")
    index += 1

Output:

Alice: 0
Bob: 1
Charlie: 2

The downside to this approach is the fact you need to remember to update the additional index variable. This introduces unnecessary code and makes the code susceptible to bugs and unintended behavior.

Because there is a separate function enumerate() dedicate to tackling this problem, it is better to use it instead.

The zip() Function

Given an iterable of elements and a separate list of indices, you can couple these two together using the zip() function.

For instance:

names = ["Alice", "Bob", "Charlie"]
indexes = [0, 1, 2]

for index, name in zip(indexes, names):
    print(f"{name}: {index}")

Output:

Alice: 0
Bob: 1
Charlie: 2

However, this is usually quite impractical due to the fact that you should specify a separate sequence for the indices.

If you do not have a separate index list, you could of course create one using the range() function and then zip it with the list:

names = ["Alice", "Bob", "Charlie"]
indexes = range(len(names))

for index, name in zip(indexes, names):
    print(f"{name}: {index}")

Output:

Alice: 0
Bob: 1
Charlie: 2

Anyway, doing this is quite useless because the built-in enumerate() function does exactly this with less code and more understandability.

The range() Function

In Python, you can use the range() function to create a range of numbers from a starting point to an end.

It is easy to loop over a range in Python.

Given the length of an iterable, you can generate a range of indexes using the range() function. Then you can use these indices to access the elements of the iterable in a for loop.

For instance:

names = ["Alice", "Bob", "Charlie"]

for i in range(len(names)):
    print(f"{names[i]}: {i}")

Output:

Alice: 0
Bob: 1
Charlie: 2

List Comprehension

Last but not least, you may have heard about list comprehensions in Python.

A list comprehension offers a one-liner shorthand for using a for loop. Using list comprehensions is never mandatory. Sometimes it can be convenient to convert a basic for loop into a short one-liner list comprehension.

Anyway, you can use list comprehension when you want to access the index of a for loop.

For instance, let’s combine a list comprehension and the enumerate() function to create a short for loop with index:

names = ["Alice", "Bob", "Charlie"]
    
[print(f"{name}: {index}") for index, name in enumerate(names)]

Output:

Alice: 0
Bob: 1
Charlie: 2

Even though this expression saves you a line of code, one could argue it looks cleaner when used as a regular for loop.

Be cautious not to sacrifice code quality with comprehensions!

Conclusion

Today you learned how to access the index in a for loop in Python.

To recap, there is a built-in enumerate() function that can be called on any iterable. It couples the elements with an index that you can use when looping through it.

In addition to using the enumerate() function, there is a bunch of (usually worse) options to looping with index:

  • Update an index variable.
  • The zip() function.
  • The range() function.
  • List comprehension.

Thanks for reading.

Happy coding!

Further Reading

50 Best Sites to Learn Coding

50 Python Interview Questions

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email