Tuples and Unpacking

A tuple is an ordered group of values.

Output:

(3, 4)

Tuples are useful for small fixed records: coordinates, pairs, short results, or values that naturally travel together.

Tuple Unpacking

Unpacking assigns the pieces of a tuple to names:

Output:

3
4

The number of names must match the number of values.

Iterating Over Tuples

Tuples often appear inside lists:

The loop unpacks each tuple as it goes.

Unpack records

Each tuple stores one small record, and the loop gives names to its parts.

Runs locally with Python in your browser.

Ready to run.

Tuples Versus Lists

Use a tuple when the positions have fixed meaning:

point = (x, y)

Use a list when you have a sequence of similar items:

scores = [8, 6, 9]

This is a guideline, not a law. The goal is readable code.

Tuple Order Carries Meaning

This fails because there are three values but only two names:

x, y = (1, 2, 3)

Unpacking needs the same number of targets as values unless you use advanced patterns later.

Exercise: Unpack a point

After this code runs, what is the value of y?

Compute it first, then check your number.

HintMatch positions

The first name receives the first value, and the second name receives the second value.

Solutiony receives ten

Unpacking matches x with 6 and y with 10, so the value of y is 10.

Unpacking Gives Positions Names

Tuples help you keep a small group of related values together. Unpacking gives those positions names.