Course Content
Python Loops Tutorial
Python Loops Tutorial
The enumerate() Function
The enumerate()
function is incredibly useful when you need to access both the value and its index in a sequence, such as a list or a string. This allows you to work with items while keeping track of their position in the sequence.
In Python, lists are ordered data structures, meaning each item has a unique index. The enumerate()
function makes it easy to retrieve both the index and the value simultaneously.
The syntax for using enumerate()
is:
index
: refers to the position of an element in the list. Python uses 0-based indexing, meaning the first element has an index of 0;value
: refers to the actual element at a given index.
Let's apply enumerate()
to our travel_list
to print each city along with its index:
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Printing all cities with their indexes for index, city in enumerate(travel_list): print(f"{index} - {city}")
Swipe to start coding
As a traveler, you have a long list of potential destinations, but you want to prioritize them based on their position in the list. To make this process easier, you decide to assign a priority ranking to each country.
- Use the
enumerate()
function to go through thecountries
list. - Assign a ranking to each country, starting from
1
. - Store the rankings in a dictionary where the country name is the key and the priority ranking is the value.
Solution
Thanks for your feedback!
The enumerate() Function
The enumerate()
function is incredibly useful when you need to access both the value and its index in a sequence, such as a list or a string. This allows you to work with items while keeping track of their position in the sequence.
In Python, lists are ordered data structures, meaning each item has a unique index. The enumerate()
function makes it easy to retrieve both the index and the value simultaneously.
The syntax for using enumerate()
is:
index
: refers to the position of an element in the list. Python uses 0-based indexing, meaning the first element has an index of 0;value
: refers to the actual element at a given index.
Let's apply enumerate()
to our travel_list
to print each city along with its index:
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Printing all cities with their indexes for index, city in enumerate(travel_list): print(f"{index} - {city}")
Swipe to start coding
As a traveler, you have a long list of potential destinations, but you want to prioritize them based on their position in the list. To make this process easier, you decide to assign a priority ranking to each country.
- Use the
enumerate()
function to go through thecountries
list. - Assign a ranking to each country, starting from
1
. - Store the rankings in a dictionary where the country name is the key and the priority ranking is the value.
Solution
Thanks for your feedback!