Transforming and Combining Data · practice
Unpack Related Values
The previous lesson introduced
result = ("Mina", 8, 10)
A
def lesson_values(lesson):
return (
lesson["title"],
lesson["chapter"],
lesson["minutes"],
)
One
details = lesson_values(lesson)
print(details[0], details[1], details[2])
When we need to use the individual values, unpacking assigns their positions to descriptive names in one step:
title, chapter, minutes = lesson_values(lesson)
print(f"Chapter {chapter}: {title} ({minutes} minutes)")
Python takes the first item for title, the second for chapter, and the third for minutes. The exercise applies the same technique to the quiz result tuple from the previous lesson.
The shapes must match
The number of names must match the number of values:
score, total = (8, 10)
Too many or too few names raises
Unpacking also works directly in a
What does this print?
point = (3, 7)
x, y = point
print(y)Format one result tuple
Complete format_result by unpacking its three-item tuple. Use the names in the requested order and return a readable score line.
Task
Complete format_result.
Unpack
resultintolearner,score, andtotal.Return
learner: score/total.Do not access the
with numeric indexes.
The hidden checks pass a new three-item tuple.