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:
>>> list(enumerate(["a", "b", "c", "d"]))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
enumerate()
Signature
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:
>>> letters = ["a", "b", "c"]
>>> for index, letter in enumerate(letters):
... print(index, letter)
...
0 a
1 b
2 c
With a custom start
value:
>>> 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:
>>> 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.
For additional information on related topics, take a look at the following resources:
- How to Write Pythonic Loops (Course)
- Python "for" Loops (Definite Iteration) (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- Python's list Data Type: A Deep Dive With Examples (Tutorial)
- Looping With Python enumerate() (Course)
- Python's enumerate() (Quiz)
- The Python for Loop (Quiz)