Python Tuple Unpacking
tuple unpackingPractice

Destructure tuples into variables

Tuple unpacking is a clean way to extract values from a tuple and assign them to individual variables. Perfect for coordinate pairs, function returns, and swapping values.

Picture this: unpack into names

Left side names line up with tuple items.

(10, 20)tuple
→
x, y = tunpack
→
x=10 y=20two variables

Diagram — unpack

(x, y) = (3, 4) x=3 y=4

In easy words: What is unpacking?

Unpacking takes the items from a tuple and gives each one its own variable. Instead of accessing with tuple[0], tuple[1], you can write x, y = tuple and use x and y directly.

Where unpacking is used

Used when extracting coordinates, getting function results with multiple values, swapping variables, iterating over lists of tuples in loops, and database queries with multiple columns.

Real world: GPS coordinates

Instead of coords[0] and coords[1], write lat, lon = coords. Now you have clear variable names. Same idea for RGB colors: red, green, blue = (255, 128, 0).

Basic Unpacking

1coords = (40.7128, -74.0060)
2lat, lon = coords
3print(lat) # 40.7128
4print(lon) # -74.0060
Interactive unpacking examples

GPS Coordinates

Step 1: Create tuple
coords = (40.7128, -74.0060)
Step 2: Unpack into variables
lat, lon = coords
Result:
lat = 40.7128 lon = -74.0060
Unpacking with underscore

Ignore unwanted values

1rgb = (255, 128, 64)
2red, _, _ = rgb # only need red
3print(red) # 255
Advanced unpacking

With asterisk (*)

1nums = (1, 2, 3, 4, 5)
2first, *rest, last = nums
3print(first) # 1
4print(rest) # [2, 3, 4]
5print(last) # 5

Unpacking in loops

1points = [(0, 0), (10, 20), (30, 40)]
2for x, y in points:
3print(f"Point: ({x}, {y})")

Example Program

1# Return multiple values from function
2def get_user_info():
3return ("Alice", 30, "NYC")
4name, age, city = get_user_info()
5print(f"{name} is {age} and lives in {city}")