enumerate()

The built-in enumerate() function adds a counter to an iterable and returns it in the form of an enumerate object, which can be directly used in loops. This function is particularly useful when you need both the index and the value of items in an iterable:

Python
>>> list(enumerate(["a", "b", "c", "d"]))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

enumerate() Signature

Python Syntax
enumerate(iterable, start=0)

Arguments

Argument Description Default Value
iterable An object that supports iteration, such as a list, tuple, or string Required argument
start The initial value of the counter 0

Return Value

  • An enumerate object that yields pairs of count and value from the iterable.

enumerate() Examples

With a list of strings as an argument:

Python
>>> letters = ["a", "b", "c"]
>>> for index, letter in enumerate(letters):
...     print(index, letter)
...
0 a
1 b
2 c

With a custom start value:

Python
>>> for count, letter in enumerate(letters, start=1):
...     print(count, value)
...
1 a
2 b
3 c

enumerate() Common Use Cases

The most common use cases for the enumerate() function include:

  • Looping through an iterable with both index and value
  • Creating counters for items in an iterable without manually managing a separate counter
  • Filter or skip specific items from an iterable based on their index

enumerate() Real-World Example

Suppose you want to check a list of strings for certain formatting issues, such as trailing whitespace or tab characters, and report these with a line number:

Python
>>> def check_whitespace(lines):
...     for lineno, line in enumerate(lines, start=1):
...         if "\t" in line:
...             print(f"Line {lineno}: Contains a tab character.")
...         if line.rstrip() != line:
...             print(f"Line {lineno}: Contains trailing whitespace.")
...

>>> check_whitespace(
...     [
...         "This is a\tline",
...         "This line is fine",
...         "Another line with a tab "
...     ]
... )
Line 1: Contains a tab character.
Line 3: Contains trailing whitespace.

This function uses enumerate() to provide a line number along with each line of text, making it easier to identify and report formatting issues. The enumerate() function simplifies the process of associating each line with a unique identifier.

Related Resources

Tutorial

Python enumerate(): Simplify Loops That Need Counters

Once you learn about for loops in Python, you know that using an index to access items in a sequence isn't very Pythonic. So what do you do when you need that index value? In this tutorial, you'll learn all about Python's built-in enumerate(), where it's used, and how you can emulate its behavior.

basics best-practices

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader