Tuples Pack Immutable Hashable Records

Pack fixed-shape records as tuples: they are immutable on assignment, hashable as dict keys, and single-element forms need the trailing comma.

PythonData Integrity

Code

pythonsnippet
21 lines
# tuple 打包定长记录:不可变、可哈希、可作 dict 键
point = (3, 4)
print("x, y =", point[0], point[1])

# 可哈希:作为字典键给坐标建索引
grid = {point: "A1", (0, 0): "origin"}
print("lookup by tuple:", grid[(3, 4)])

# 不可变:修改元素直接 TypeError
try:
    point[0] = 9
except TypeError as exc:
    print("immutable:", exc)

# 单元素必须带逗号,否则只是加了括号的表达式
single = (42,)
print("single is tuple:", isinstance(single, tuple), "| (42) is:", type(42).__name__)

# 解包与星号收集:定长头 + 任意尾
first, *rest = (1, 2, 3, 4)
print("head:", first, "| rest:", rest)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

x, y = 3 4
lookup by tuple: A1
immutable: 'tuple' object does not support item assignment
single is tuple: True | (42) is: int
head: 1 | rest: [2, 3, 4]

How it works

Top-level bindings point, grid, single hold the demo state — nothing sits inside a function scope.

Caveats

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

Output lines are prefixed (x, y =, lookup by tuple:, immutable:), with the prefixes making the order obvious.

Key statements

except TypeError as exc:
    print("immutable:", exc)

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `point`, `grid`, `single`.