Using * and zip to 'unzip'
You know how to use zip()
as well as how to print out values from a zip
object. Excellent!
Let's play around with zip()
a little more. There is no unzip function for doing the reverse of what zip()
does. We can, however, reverse what has been zip
ped together by using zip()
with a little help from *
! *
unpacks an iterable such as a list or a tuple into positional arguments in a function call.
In this exercise, you will use *
in a call to zip()
to unpack the tuples produced by zip()
.
Two tuples of strings, mutants
and powers
have been pre-loaded.
This exercise is part of the course
Python Toolbox
Exercise instructions
- Create a
zip
object by usingzip()
onmutants
andpowers
, in that order. Assign the result toz1
. - Print the tuples in
z1
by unpacking them into positional arguments using the*
operator in aprint()
call. - Because the previous
print()
call would have exhausted the elements inz1
, recreate thezip
object you defined earlier and assign the result again toz1
. - 'Unzip' the tuples in
z1
by unpacking them into positional arguments using the*
operator in azip()
call. Assign the results toresult1
andresult2
, in that order. - The last
print()
statements prints the output of comparingresult1
tomutants
andresult2
topowers
. ClickSubmit Answer
to see if the unpackedresult1
andresult2
are equivalent tomutants
andpowers
, respectively.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a zip object from mutants and powers: z1
z1 = ____
# Print the tuples in z1 by unpacking with *
print(____)
# Re-create a zip object from mutants and powers: z1
z1 = ____
# 'Unzip' the tuples in z1 by unpacking with * and zip(): result1, result2
result1, result2 = ____
# Check if unpacked tuples are equivalent to original tuples
print(result1 == mutants)
print(result2 == powers)