Skip to content

Python Tuples

不可变序列使用 tuples: creation, packing, unpacking, and 当到 use 它们 over 列表.

你将学到

  • 创建 tuples and 理解 immutability
  • Pack and unpack tuples for 多个值
  • Use tuples as dictionary 键 and 设置元素
  • Access and slice tuples 如列表
  • Know 当到 选择 tuples over 列表

概念讲解

Creating Tuples

tuple 是一种 ordered, immutable sequence. Once created, you cannot add, remove, or change its elements:

empty = ()
single = (42,)          # note the comma — (42) is just an int!
point = (10, 20)
mixed = (1, "hello", True)
nested = ((1, 2), (3, 4))

The trailing comma in (42,) is critical — without it, Python interprets (42) as just the integer 42 in parentheses. This is a common source of confusion for beginners.

Immutability

Tuples cannot be modified after creation:

point = (10, 20)
# point[0] = 5  # TypeError: 'tuple' object does not support item assignment
# point.append(30)  # AttributeError: tuples have no append

This immutability has two benefits:

  1. Safety — you can be sure the data will not change accidentally
  2. Hashability — tuples can be used as dict keys and set elements (lists cannot)

Packing and Unpacking

Python's tuple unpacking is one of its most elegant features:

# Packing — creating a tuple
point = 10, 20  # parentheses are optional!

# Unpacking — extracting values
x, y = point
print(x, y)  # 10 20

# Swap variables
a, b = 1, 2
a, b = b, a  # now a=2, b=1

# Multiple return values from a function
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5])

Functions that return multiple values are actually returning a tuple — Python automatically packs the values, and you unpack them on the receiving end. This is cleaner than returning a list or a custom object for simple cases.

Extended Unpacking

Python 3 introduced star unpacking for grabbing parts of a sequence:

first, *rest = [1, 2, 3, 4, 5]
# first=1, rest=[2, 3, 4, 5]

first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2, 3, 4], last=5

The * collects remaining elements into a list. This is useful for ignoring or capturing variable-length portions.

Indexing and Slicing

Tuples support the same indexing and slicing as lists:

point = (10, 20, 30)
print(point[0])     # 10
print(point[-1])    # 30
print(point[0:2])   # (10, 20)
print(len(point))   # 3

Tuples as Dict Keys

Because tuples are hashable, they can be used as dictionary keys — lists cannot:

grid = {}
grid[(0, 0)] = "原点"
grid[(1, 2)] = "点 "
print(grid[(0, 0)])  # origin

This is common for coordinate-based data, sparse matrices, and caching by multiple parameters.

When to Use Tuples vs Lists

  • Use a tuple for fixed collections that should not change: coordinates, RGB colors, days of the week, function returns
  • Use a list when you need to add, remove, or modify elements

Tuples are also slightly faster and use less memory than lists, which matters for large datasets.

示例代码

              # Creating tuples
empty = ()
single = (42,)        # trailing comma needed for single-item tuple
point = (10, 20)
mixed = (1, "hello", True)
print(point, mixed)

# Immutability — these would raise errors:
# point[0] = 5  # TypeError

# Packing and unpacking
coordinates = 10, 20  # packing (parens optional)
x, y = coordinates     # unpacking
print(f"x={x}, y={y}")

# Swap variables
a, b = 1, 2
a, b = b, a
print(f"Swapped: a={a}, b={b}")

# Multiple return values
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5])
print(f"Min={low}, Max={high}")

# Extended unpacking
first, *rest = [1, 2, 3, 4, 5]
print(f"first={first}, rest={rest}")

# Tuples as dict keys
grid = {}
grid[(0, 0)] = "origin"
grid[(1, 2)] = "point A"
print(grid[(0, 0)])

# Indexing and slicing
data = (10, 20, 30, 40, 50)
print(data[0:3])   # (10, 20, 30)
print(data[::-1])  # reversed
            

Shows tuple creation (包含单个-项 comma gotcha), packing/unpacking, 变量 swapping, 多个返回值, extended star-unpacking, tuples as dict 键, and slicing.

动手试一试

  • JSON Formatter

    Tuples serialize 到 JSON 数组 — inspect 它们的结构.

  • 情况 Converter

    Unpacking 是 useful for 拆分 and recombining 文本部分.

常见错误

错误写法

编写 (42) expecting 单个-元素 tuple

正确做法

(42) 是只是 integer 42 in parentheses. 单个-元素 tuple 需要 trailing comma: (42,). 这个是 one 的大多数常见 tuple pitfalls for 初学者.

错误写法

Trying 到修改 tuple 使用 append or 项 assignment

正确做法

Tuples 是不可变 — 它们有 否 append, insert, or 移除方法, and 项 assignment raises TypeError. 如果你 需要到 修改集合, use 列表相反.

相关速查表

练习 Python Tuples

2 个练习

练习 Python Tuples

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误