Using and unpacking tuples
If you have a tuple like ('chocolate chip cookies', 15)
and you want to access each part of the data, you can use an index just like a list. However, you can also "unpack" the tuple into multiple variables such as type, count = ('chocolate chip cookies', 15)
that will set type
to 'chocolate chip cookies'
and count
to 15
.
Often you'll want to pair up multiple array data types. The zip()
function does just that. It will return a list of tuples containing one element from each list passed into zip()
.
When looping over a list, you can also track your position in the list by using the enumerate()
function. The function returns the index of the list item you are currently on in the list and the list item itself.
(We'll talk more about the last line of code in our next lesson)
This exercise is part of the course
Data Types in Python
Exercise instructions
- Use the
zip()
function to pair upgirl_names
andboy_names
into a variable calledpairs
. - Use a
for
loop to loop throughpairs
, usingenumerate()
to keep track of your position. Unpackpairs
into the variablesrank
andpair
. - Unpack
pair
into the variablesgirl_name
andboy_name
. - Print the rank, girl name, and boy name, in that order. The rank is contained in
rank
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Pair up the girl and boy names: pairs
pairs = ____
# Iterate over pairs
for ____, ____ in ____:
# Unpack pair: girl_name, boy_name
____, ____ = ____
# Print the rank and names associated with each rank
print(f'Rank {rank+1}: {girl_name} and {boy_name}')