Sitemap

Member-only story

Enumerate Function in Python

2 min readApr 28, 2024

--

The enumerate() function in Python is a built-in function that allows you to iterate over an iterable (such as a list, tuple, or string) while also keeping track of the index of each item in the iterable.

Here’s how enumerate() works:

# Syntax
enumerate(iterable, start=0)

# Example
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(index, value)

# Output
# 0 apple
# 1 banana
# 2 cherry

In this example:
my_list is a list of strings [‘apple’, ‘banana’, ‘cherry’].
we use the enumerate() function to iterate over my_list.
In each iteration, enumerate() yields a tuple containing the index and value of the current item in the list.
We unpack this tuple into index and value variables.
Inside the loop, we print the index and value of each item in the list.

Advantages: The enumerate() function is particularly useful when you need to iterate over the elements of an iterable and also require access to the index of each element. It simplifies the code compared to manually managing the index variable in a loop. Additionally, the start parameter allows you to specify the starting index for enumeration, which defaults to 0 if not provided.

Example 1: Enumerating a List

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(f"Index {index}: {value}")…

--

--

Rina Mondal
Rina Mondal

Written by Rina Mondal

I truly enjoy writing articles. If you appreciate my hard work, please follow me. Your encouragement helps me continue pursuing my passion.