Skip to content

Tuples in Python

A tuple is an immutable, ordered sequence — like a list that can never be changed. This immutability makes tuples faster, hashable, and semantically meaningful.

empty = ()
point = (3, 4)
person = ("Alice", 30, "Engineer")
# Parentheses optional
coords = 10, 20
# Single element tuple NEEDS comma
single = (42,) # Tuple
not_tuple = (42) # Just integer 42!
point = 3, 4 # Packing
x, y = point # Unpacking
print(x, y) # 3 4
# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
print(rest) # [2, 3, 4, 5] (rest is list!)
# Swap
x, y = 10, 20
x, y = y, x
t = (3, 1, 4, 1, 5, 9, 2, 6, 5)
print(t.count(1)) # 2
print(t.index(5)) # 4
print(5 in t) # True
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x) # 3 — clear!
print(p.y) # 4
print(p[0]) # 3 — still supports indexing
# From typing (Python 3.6+)
from typing import NamedTuple
class Point3D(NamedTuple):
x: float
y: float
z: float = 0.0
FeatureTupleList
MutabilityImmutableMutable
MemorySmaller (~33% less)More
HashableYes (dict key)No
Methods2 (count, index)11+
CreationFaster (~5x)Slower

Tuples are ideal for fixed data (coordinates, RGB colors, database records) and as dictionary keys.

Q1: Why are tuples faster than lists?

A: Tuples are stored more compactly with no over-allocation. Constant tuples can be reused. Iteration is optimized in CPython.

Q2: Can a tuple contain mutable elements?

A: Yes! A tuple with a list inside can have that list modified: t = ([1,2], 3); t[0].append(4) — this works!

  1. Create a named tuple for 2D coordinates and calculate distance.
  2. Demonstrate the difference between == and is with tuples.
  3. Compare memory usage of a tuple vs list with the same data.