The enumerate
function is a built-in function in Python that simplifies looping through sequences (such as lists, tuples, or strings) by providing both the index and the value of each element in the sequence.
This makes it an efficient and clean way to access both the element and its position during iteration.
Basic Usage
The enumerate
function returns a sequence of tuples, where each tuple contains:
- The index of the element
- The value of the element
Syntax:
enumerate(iterable, start=0)
iterable
: The sequence you want to iterate over (e.g., list, tuple, string)start
(optional): Specifies the starting index (default is0
)
Example:
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 mango
Customizing the Start Index
By default, the enumerate function starts the index at 0, but you can change the starting index by passing a value for the start
parameter.
For example:
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 apple
2 banana
3 mango
Common Use Cases
1. Numbered Output
When you need to print a sequence with numbered items:
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits, start=1):
print(f'{index}: {fruit}')
Output:
1: apple
2: banana
3: mango
2. Enumerating Tuples
The enumerate
function works seamlessly with tuples.
colors = ('red', 'green', 'blue')
for index, color in enumerate(colors):
print(index, color)
Output:
0 red
1 green
2 blue
3. Enumerating Strings
Strings are iterable, so you can use enumerate
to loop over their characters.
s = 'hello'
for index, char in enumerate(s):
print(index, char)
Output:
0 h
1 e
2 l
3 l
4 o
👉 Next tutorial: Python Local and Global Variables