Python3 元组

Why immutability matters, the single-element comma, unpacking, and named tuples.

Beginner
Key PointsTuples are immutable and therefore hashable — they can be dict keys and set members; the one-element form needs a trailing comma.

Basics

Python
point = (3, 4)
single = (42,)        # 注意逗号!(42) 只是整数 42
empty = ()

point[0]              # 3
x, y = point          # 解包
a, b = b, a           # 交换变量,不需要临时变量

Why Immutable

  • Safe to share: nobody can mutate your tuple behind your back.
  • Hashable: usable as dict keys and set members.
  • Faster and smaller than an equivalent list.
  • Signals intent: a fixed record, not a growing collection.
Python
locations = {}
locations[(39.9, 116.4)] = "Beijing"     # 元组当键
print(locations[(39.9, 116.4)])

# point[0] = 5  -> TypeError: 'tuple' object does not support item assignment

Unpacking

Unpacking works anywhere an iterable appears: assignment, function arguments, loop targets, and with * to collect the rest.

Python
first, *rest = [1, 2, 3, 4]        # 1  [2, 3, 4]
head, *middle, tail = "abcdef"     # 'a' ['b','c','d','e'] 'f'

def area(width, height):
    return width * height

size = (3, 4)
print(area(*size))                 # 12,用 * 展开

Named Tuples

namedtuple gives fields a name while keeping tuple behaviour (immutable, unpackable, indexable). For new code, dataclass(frozen=True) is the more capable option.

Python
from collections import namedtuple

Point = namedtuple("Point", "x y")
pt = Point(3, 4)
print(pt.x, pt[0], pt)        # 3 3 Point(x=3, y=4)
print(pt._asdict())           # {'x': 3, 'y': 4}
A one-element tuple needs (x,). (x) is just a parenthesised expression — a classic silent bug.

Friends & Partners