6️⃣

14.6 Enumerate

Enumerate

You can use enumerate to keep track of the index of the elements in a list. Although you can do this yourself, using enumerate takes less time and is more elegant. In other languages, enumerate doesn’t exist However, python provides enumerate as a built-in function. Take a look.
countries = [' Japan', 'America', 'South Korea', ' China'] numerated_list = list(enumerate(countries)) print(numerated_list) # prints [(0, ' Japan'), (1, 'America'), (2, 'South Korea'), (3, ' China')]
Here, we modified the list to have the element's index in the element, as seen in how 0 is paired with 'Japan'
 
Here's an example of when we want to keep track of the index using enumerate
# This code gets all the countries with even indexes greater than 1 answer_list = [] for index, country in enumerate(countries): if index % 2 == 0 and index > 1: answer_list.append(country) print(answer_list) # prints ['South Korea']
As you can see here, we were able to make good use of the index that is being kept track by the enumerate function. Also, if you haven’t noticed, we used tuple unpacking here in the for loop line. We unpacked the index and the country for each of the countries from enumerate(countries). As you can see, tuple unpacking is pretty useful.
View code on GitHub.

Practice

Bob's Selection

Bob is choosing a person to go to the moon with him. The way he chooses is quite strange. He will choose the first person from a list given to him whose age is divisible by 5 and whose index within the list is divisible by 5. If he does find such a person, print the person’s name. If he doesn’t, don’t print anything. The list given to him contains lists which in turn contain the person’s name and age. Use enumerate to solve this problem.

Worried Josh

Josh is worried about his test score. He wants to score in the top n, where n is a positive integer that the user inputs. Given a list of student names where the student with the highest score is the 0th index and the score goes down from there, print “YES!” if Josh scores in the top n, and “NO :(“ if he doesn’t. Assume n will not be greater than the number of students. Use enumerate to solve this problem.

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.