元组是Python中一种不可变的有序序列数据类型,与列表(list)类似,但元组一旦创建就不能修改。
基本特性
- 不可变性:元组创建后不能修改其元素
- 有序性:元素按照插入顺序存储
- 可包含任意类型:可以包含数字、字符串、列表等其他元组等
- 用圆括号表示:通常用
()定义,但括号不是必需的
创建元组
# 空元组
empty_tuple = ()
empty_tuple = tuple()
# 单个元素的元组(注意逗号)
single_tuple = (1,) # 正确
not_a_tuple = (1) # 这不是元组,只是整数1
# 多元素元组
fruits = ('apple', 'banana', 'cherry')
numbers = 1, 2, 3 # 括号可以省略
# 从其他序列创建
tuple_from_list = tuple([1, 2, 3])
tuple_from_str = tuple("hello")访问元组元素
colors = ('red', 'green', 'blue')
# 索引访问
print(colors[0]) # 输出: red
print(colors[-1]) # 输出: blue
# 切片操作
print(colors[1:]) # 输出: ('green', 'blue')元组操作
# 连接元组
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b')
combined = tuple1 + tuple2 # (1, 2, 3, 'a', 'b')
# 重复元组
repeated = tuple1 * 2 # (1, 2, 3, 1, 2, 3)
# 成员检测
print(2 in tuple1) # True
print('x' not in tuple1) # True
# 长度
print(len(tuple1)) # 3元组方法
由于元组不可变,方法比列表少:
t = (1, 2, 2, 3)
# count() - 计算元素出现次数
print(t.count(2)) # 输出: 2
# index() - 返回元素第一次出现的索引
print(t.index(3)) # 输出: 3元组解包
# 基本解包
point = (10, 20)
x, y = point
print(x, y) # 10 20
# 使用*收集剩余元素
first, *rest = (1, 2, 3, 4)
print(first) # 1
print(rest) # [2, 3, 4]
# 交换变量
a, b = b, a # 不需要临时变量元组与列表的比较
特性 | 元组(Tuple) | 列表(List) |
可变性 | 不可变 | 可变 |
语法 | 使用 | 使用 |
性能 | 更快 | 稍慢 |
内存占用 | 更小 | 更大 |
适用场景 | 固定数据 | 可变数据 |
使用场景
- 保证数据不被修改:当需要确保数据不被意外更改时
- 字典键:元组可以作为字典的键,而列表不行
- 函数返回多个值:函数可以返回元组来传递多个值
- 性能优化:处理大量数据时,元组比列表更高效
# 作为字典键
locations = {
(35.6895, 139.6917): "Tokyo",
(40.7128, -74.0060): "New York"
}
# 函数返回多个值
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)/len(numbers)元组是Python中非常有用的数据结构,特别适合存储不应更改的数据集合。
















