Lecture

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 refers to the index of the element in the iterable, and element refers to the element at that index.


How do you use the enumerate function?

The enumerate function takes an iterable as an argument and returns the elements of the iterable along with their indices as it iterates.

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}")
Mission
0 / 1

Which statement correctly describes the enumerate function?

It sorts an iterable.

It removes all elements from an iterable.

It traverses an iterable and provides both the index and the element.

It reverses the elements of an iterable.

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result