Legends ofPythos
Claim your name
Working with Data

Tuples and unpacking

Lesson 2 of 14

Watch the lesson1:27 ยท with Torsten
A tuple is an ordered collection of values, written with parentheses. Unlike a list you can rearrange or edit at any time, a tuple is locked once created. You cannot change its items in place.

Mental model: the sealed envelope

Think of a tuple as an envelope with a wax seal on it. Once you drop letters inside and close it, those exact papers stay put until someone tears the whole thing open to read them all at once. A list is like a loose folder where pages can slide in or out.

Why tuples matter

You will use tuples whenever you need to return several related results from one function, such as the best score and the player name who earned it. Because they cannot be altered by accident, other code can trust that those values stay fixed.

Creating a tuple

point = (3, 7)
print(point[0])
# Accessing by index still works
print(type(point))
# It is a tuple, so its items can't be changed
A sealed record of two numbers
The code above stores the pair three and seven. You can read either value using an index, but you cannot replace one with a new number.

Unpacking: opening the envelope

x, y = (3, 7)
print(x)
# First value lands in x
name, score, passed = ('Bob', 8, True)
print(name)
Splitting sealed values into named variables
Unpacking opens the envelope and places each item into its own named variable. The left side must have exactly as many names as there are items inside.

Swapping in one line

a = 1
b = 2
print(a, b)
# Show the original order
a, b = b, a
print(a, b)
Exchanging two values without a helper
Python builds a temporary tuple on the right side of that assignment. Both variables update simultaneously from that snapshot.

Returning multiple values

def swap(a, b):
    return b, a

current = (50, 12)
left, right = current      # unpack the tuple first
after = swap(left, right)
print(after)               # (12, 50)
A function hands back two results
The function returns the arguments in reverse order, as one tuple, which the caller keeps in after.

Your turn

0 of 3 solved

Exercise 1

+25 XP
Create a tuple called point with the values (3, 7). Unpack it into two variables named x and y. Then print the sum of x and y.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+25 XP
Write a function called swap that takes two arguments (a and b) and returns them swapped as a tuple. Then call it with values 10 and 99, unpack the result into variables first and second, and print both.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+25 XP
Create a tuple called record with the values ('Bob', 8, True). Unpack it into three variables: name, score, and passed. Then print an f-string in this exact format: Name: Bob | Score: 8 | Passed: True (replace values with your unpacked variables).
Write your Python here.

Run your code to check it against the tests.