0%

Transforming and Combining Data · practice

Unpack Related Values

The previous lesson introduced as small, ordered groups of fixed values. Its result tuple kept a learner name, score, and total together:

result = ("Mina", 8, 10)

A can build and return another three-item record:

def lesson_values(lesson):
    return (
        lesson["title"],
        lesson["chapter"],
        lesson["minutes"],
    )

One can receive the whole returned tuple:

details = lesson_values(lesson)

works, but the meaning of each position is not visible:

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 . This strictness is useful when the tuple has a known shape. A mismatch reveals that the caller and function no longer agree.

Unpacking also works directly in a :

Try it

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 result into learner, score, and total.

  • Return learner: score/total.

  • Do not access the with numeric indexes.

The hidden checks pass a new three-item tuple.