Notes

`enumerate()` Function in Python [ English ]

< Prev Next >

1. Introduction

The enumerate() function in Python is a built-in function used to add a counter to an iterable object such as a list, tuple, or string. It returns an enumerate object, which produces pairs containing the index and the corresponding element from the iterable.

The enumerate() function is very useful when we need to access both the index and value of elements while iterating through a sequence, especially in loops.

2. Syntax

enumerate(iterable, start=0)

Parameters

  1. iterable Any iterable object such as a list, tuple, string, or dictionary.

  2. start (optional) The starting value of the counter. By default, the counter starts from 0.

Return Value

3. Basic Example

fruits = ["apple", "banana", "mango"]

result = enumerate(fruits)

print(list(result))

Output

[(0, 'apple'), (1, 'banana'), (2, 'mango')]

Explanation

4. Using enumerate() in a Loop

fruits = ["apple", "banana", "mango"]

for index, value in enumerate(fruits):
    print(index, value)

Output

0 apple
1 banana
2 mango

Explanation

5. Example with Starting Index

names = ["Rahul", "Amit", "Priya"]

for i, name in enumerate(names, start=1):
    print(i, name)

Output

1 Rahul
2 Amit
3 Priya

Explanation

6. Example with a String

text = "Python"

for index, char in enumerate(text):
    print(index, char)

Output

0 P
1 y
2 t
3 h
4 o
5 n

Explanation

7. Example with a Tuple

numbers = (10, 20, 30)

for index, value in enumerate(numbers):
    print(index, value)

Output

0 10
1 20
2 30

8. Why enumerate() is Useful

Without enumerate():

fruits = ["apple", "banana", "mango"]

for i in range(len(fruits)):
    print(i, fruits[i])

With enumerate():

for i, fruit in enumerate(fruits):
    print(i, fruit)

Advantage

9. Summary

< Prev Next >