Tuple
一句话解释
tuple 是有序, 不可变集合的 项 in Python, 编写 as (1, 2, 3).
用大白话说
tuple 是如 列表那个你 cannot 更改. 一次你 创建 tuple, 它的大小 and 内容是 fixed — 你 cannot 添加, 移除, or reassign 元素. Tuples 是编写使用 parentheses: (1, 2, 3).
Tuples are used for fixed records where immutability is a feature — coordinates (x, y), RGB color values (255, 128, 0), or database rows. Because they cannot change, they are hashable and can be used as dictionary keys, which lists cannot.
Tuples are slightly faster and use less memory than lists. When you have a collection that should never change, a tuple signals that intent more clearly than a list. A tuple with one element needs a trailing comma: (5,).
示例
point = (3, 4)
color = (255, 128, 0)
print(point[0]) # 3
print(len(color)) # 3
# Tuples are immutable — this raises an error:
# point[0] = 10 # TypeError
# Tuples can be unpacked
x, y = point
print(x, y) # 3 4Tuples support indexing and unpacking 但 cannot 是修改之后 creation.
常见混淆
容易混淆的对象: 列表
关键区别: tuple 是不可变 — 它 cannot 是更改之后 creation. 列表是 可变 — 你能 添加, 移除, and reassign 元素. Use tuples for fixed 数据, 列表 for 数据那个更改.
相关术语
相关资源
相关课程
- 数据类型
Tuples 是核心 Python 数据类型
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。