Using enumerate
You're really getting the hang of using iterators, great job!
You've just gained several new ideas on iterators from the last video and one of them is the enumerate() function. Recall that enumerate() returns an enumerate object that produces a sequence of tuples, and each of the tuples is an index-value pair.
In this exercise, you are given a list of strings mutants and you will practice using enumerate() on it by printing out a list of tuples and unpacking the tuples using a for loop.
This exercise is part of the course
Python Toolbox
Exercise instructions
- Create a list of tuples from
mutantsand assign the result tomutant_list. Make sure you generate the tuples usingenumerate()and turn the result from it into a list usinglist(). - Complete the first
forloop by unpacking the tuples generated by callingenumerate()onmutants. Useindex1for the index andvalue1for the value when unpacking the tuple. - Complete the second
forloop similarly as with the first, but this time change the starting index to start from1by passing it in as an argument to thestartparameter ofenumerate(). Useindex2for the index andvalue2for the value when unpacking the tuple.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a list of strings: mutants
mutants = ['charles xavier',
'bobby drake',
'kurt wagner',
'max eisenhardt',
'kitty pryde']
# Create a list of tuples: mutant_list
mutant_list = ____
# Print the list of tuples
print(mutant_list)
# Unpack and print the tuple pairs
for ____ in ____:
print(index1, value1)
# Change the start index
for ____ in ____:
print(index2, value2)