Using zip
Another interesting function that you've learned is zip(), which takes any number of iterables and returns a zip object that is an iterator of tuples. If you wanted to print the values of a zip object, you can convert it into a list and then print it. Printing just a zip object will not return the values unless you unpack it first. In this exercise, you will explore this for yourself.
Three lists of strings are pre-loaded: mutants, aliases, and powers. First, you will use list() and zip() on these lists to generate a list of tuples. Then, you will create a zip object using zip(). Finally, you will unpack this zip object in a for loop to print the values in each tuple. Observe the different output generated by printing the list of tuples, then the zip object, and finally, the tuple values in the for loop.
This exercise is part of the course
Python Toolbox
Exercise instructions
- Using
zip()withlist(), create a list of tuples from the three listsmutants,aliases, andpowers(in that order) and assign the result tomutant_data. - Using
zip(), create a zip object calledmutant_zipfrom the three listsmutants,aliases, andpowers. - Complete the
forloop by unpacking thezipobject you created and printing the tuple values. Usevalue1,value2,value3for the values from each ofmutants,aliases, andpowers, in that order.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a list of tuples: mutant_data
mutant_data = ____
# Print the list of tuples
print(mutant_data)
# Create a zip object using the three lists: mutant_zip
mutant_zip = ____
# Print the zip object
print(mutant_zip)
# Unpack the zip object and print the tuple values
for ____ in ____:
print(value1, value2, value3)