Member-only story
Enumerate Function in Python
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 cherryIn 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}")…







