Syllabus Lesson 30 of 239 · Data Structures
Data Structures

Tuples and Unpacking

A tuple is like a list but immutable: once made, it cannot change. You write it with parentheses (or just commas).

point = (3, 4)
print(point[0])   # 3
print(len(point)) # 2

Because tuples never change, they are great for fixed groups of values, like a coordinate or an (x, y) pair. Trying to assign to one raises an error.

Unpacking pulls the items into separate variables in one line:

pair = (10, 20)
a, b = pair
print(a)   # 10
print(b)   # 20

This makes the classic swap trick possible without a temporary variable:

x = 1
y = 2
x, y = y, x
print(x, y)   # 2 1

A function can return several values as a tuple, and you unpack them the same way.

Your turn

Given pair = ("width", 80), unpack it into variables label and value. Then set x = 1 and y = 9 and swap them in a single line so x becomes 9 and y becomes 1.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output