Iterating Over Elements of an Iterable
The enumerate
function is used to iterate over an iterable object like a list or tuple, returning both the element and its index
.
It's commonly used with a for loop as shown below.
Using enumerate function in a for loop
for index, element in enumerate(iterable):
... # body of the loop
Between the for
keyword and the in
keyword, two variables such as index
and element
are used.
index
represents the position of an element in the iterable, while element
refers to the value at that position.
How do you use the enumerate function?
The enumerate
function takes an iterable as an argument and returns its elements along with their indices during iteration.
Example of using enumerate function
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
The enumerate
function is useful when you need index information for each element of the list, or when you want to perform different actions based on the index.
Using enumerate function with a loop
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
# Execute if the index is 0 or even
if index % 2 == 0:
print(f"index: {index}, fruit: {fruit}")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.