Python3 元组
Why immutability matters, the single-element comma, unpacking, and named tuples.
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 assignmentUnpacking
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.基础
Python
point = (3, 4)
single = (42,) # 注意逗号!(42) 只是整数 42
empty = ()
point[0] # 3
x, y = point # 解包
a, b = b, a # 交换变量,不需要临时变量为什么不可变
- 可安全共享:没人能在背后改掉它。
- 可哈希:能作为字典键和集合元素。
- 比等长列表更快、更省内存。
- 表达意图:这是固定记录,不是会增长的集合。
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解包
解包适用于任何可迭代对象出现的位置:赋值、函数传参、循环目标,配合 * 可以收集剩余元素。
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,用 * 展开命名元组
namedtuple 给字段起名字,同时保留元组特性(不可变、可解包、可索引)。新代码可以用更强的 dataclass(frozen=True)。
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}单元素元组必须写
(x,)。(x) 只是带括号的表达式 —— 经典的静默 bug。