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 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}")
#Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Example 2: Enumerating a Tuple
my_tuple = ('apple', 'banana', 'cherry')
for index, value in enumerate(my_tuple, start=1):
print(f"Item {index}: {value}")
# Output:
Item 1: apple
Item 2: banana
Item 3: cherry
Example 3: Enumerating a String
my_string = "hello"
for index, char in enumerate(my_string):
print(f"Character {index}: {char}")
#Output:
Character 0: h
Character 1: e
Character 2: l
Character 3: l
Character 4: o
Example 4: Enumerating a List of Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for i, row in enumerate(matrix):
for j, value in enumerate(row):
print(f"Matrix[{i}][{j}] = {value}")
# Output:
Matrix[0][0] = 1
Matrix[0][1] = 2
Matrix[0][2] = 3
Matrix[1][0] = 4
Matrix[1][1] = 5
Matrix[1][2] = 6
Matrix[2][0] = 7
Matrix[2][1] = 8
Matrix[2][2] = 9
Examples 5: Enumerate a Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
for index, (key, value) in enumerate(my_dict.items()):
print(index, key, value)
These examples showcase different use cases of enumerate() with various types of iterables such as lists, tuples, strings, and nested lists. The enumerate() function provides a concise and elegant way to iterate over elements while simultaneously tracking their indices.