iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Tuples

A tuple is an ordered, immutable sequence. Great for "a record of related values" — coordinates, RGB triples, return values that group related data.

Create

PYTHON
point  = (3, 4)
single = (42,)         # comma is required — (42) is just an int in parens
empty  = ()

Unpack

PYTHON
x, y      = (3, 4)
first, *rest = (1, 2, 3, 4, 5)   # first=1, rest=[2,3,4,5]
a, b = b, a                       # swap — classic idiom

Tuple vs list

TupleList
ImmutableMutable
Slightly fasterSlightly slower
Hashable — usable as dict keys, set membersNot hashable
"A record""A collection that can grow"

Named tuples (nicer records)

PYTHON
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y, p)        # 3 4 Point(x=3, y=4)

Modern alternative: dataclasses for mutable records, or typing.NamedTuple for typed immutable ones.

Tip: Functions can return multiple values via a tuple: return name, age. The caller unpacks it: name, age = get_user().

Example

Example
point = (3, 4)
x, y = point      # unpacking
print(x, y)
print(len(point))
# tuples are immutable
# point[0] = 5  # would raise TypeError
Try it Yourself »

Exercise

Make a single-element tuple containing 42.

t = (42 )

Test yourself

Q1. A single-element tuple is…
Q2. Tuples are useful as dict keys because they are…
Q3. *rest in unpacking captures…

Discussion

Loading…