Introduction to Python Tuples 元组介绍

What is a Tuple in Python?

In Python, a tuple is a fundamental (基础的) data structure that stores an ordered collection of items. Unlike lists, tuples are immutable (不可变的), meaning their contents cannot be changed after creation. Tuples are defined using parentheses () and items are separated by commas. They are useful for storing data that should remain constant (恒定的), such as configuration settings or records (记录) in a database.

Create a Tuple

You can create a tuple by putting items inside (). For example:

# A tuple of numbers
numbers = (1, 2, 3, 4, 5)

# A tuple of strings
colors = ("red", "green", "blue")

# A mixed tuple (contains numbers, string, and None)
mixed_tuple = (100, "hello", None)

# An empty tuple
empty_tuple = ()

# A tuple with one item (note the trailing comma)
single_item_tuple = (5,)  # Without the comma, it's just a number in parentheses

Access Items in a Tuple

Like lists, tuple items have indexes for positioning. Python uses zero-based indexing, so the first item is at index 0. You can access items using square brackets, just like with lists.

colors = ("red", "green", "blue")
print(colors[0])  # Output: red
print(colors[2])  # Output: blue

Negative indexes work the same way, allowing access from the end of the tuple.

print(colors[-1])  # Output: blue
print(colors[-2])  # Output: green

Why Are Tuples Immutable?

Once a tuple is created, you cannot modify, add, or remove its items. Trying to change a tuple will cause an error:

colors = ("red", "green", "blue")
colors[1] = "yellow"  # This will raise a TypeError: 'tuple' object does not support item assignment

This immutability makes tuples safer for data that should not be accidentally changed, such as coordinates (坐标) or fixed parameters (参数).

Common Tuple Operations

Although tuples are immutable, you can still perform some operations:

  1. Concatenation (合并): Combine two tuples using +.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple)  # Output: (1, 2, 3, 4, 5, 6)
  1. Repetition (重复): Repeat a tuple using *.
single_color = ("red",)
repeated_tuple = single_color * 3
print(repeated_tuple)  # Output: ('red', 'red', 'red')
  1. Check Item Existence: Use the in keyword to check if an item is present.
colors = ("red", "green", "blue")
print("green" in colors)  # Output: True
print("yellow" in colors)  # Output: False
  1. Tuple Length: Get the number of items with the len() function.
print(len(colors))  # Output: 3

Tuple Methods

Tuples have two main methods:

  • count(value): Returns the number of times a value appears in the tuple.
numbers = (1, 2, 2, 3, 3, 3)
print(numbers.count(2))  # Output: 2
  • index(value): Returns the first index where a value appears.
print(colors.index("green"))  # Output: 1

Unpacking Tuples (元组解包)

One powerful feature of tuples is unpacking, which allows you to assign the items of a tuple to variables directly.

# Unpack a tuple into variables
coordinates = (10, 20)
x, y = coordinates  # x becomes 10, y becomes 20
print(x, y)  # Output: 10 20

# Unpack a tuple with more items
person = ("Alice", 30, "engineer")
name, age, job = person
print(name, age, job)  # Output: Alice 30 engineer

Tuples vs. Lists: When to Use Which?

Feature

Tuple

List

Mutability (可变性)

Immutable (不可变)

Mutable (可变)

Syntax (语法)

Uses ()

Uses []

Use Cases

Store fixed data (存储固定数据)

Store changeable data (存储可变数据)

Performance (性能)

Faster for iteration (遍历更快)

Slightly slower (稍慢)

Example: Using Tuples for Records

Tuples are ideal for storing records that shouldn't change, like a student's information:

student = ("Bob", 18, "Math", 90.5)
# Unpack the tuple to display information
name, age, subject, score = student
print(f"{name} is {age} years old, studying {subject} with a score of {score}.")
# Output: Bob is 18 years old, studying Math with a score of 90.5.

Python元组介绍

什么是Python中的元组?

在Python中,元组(tuple)是一种基础的数据结构,用于存储有序的元素集合。与列表不同,元组是不可变的(immutable),这意味着创建后无法修改其内容。元组用括号()定义,元素之间用逗号分隔。它们适用于存储需要保持不变的数据,例如配置设置或数据库中的记录(records)。

创建元组

你可以通过在()中放入元素来创建元组。例如:

# 数字元组
numbers = (1, 2, 3, 4, 5)

# 字符串元组
colors = ("red", "green", "blue")

# 混合元组(包含数字、字符串和None)
mixed_tuple = (100, "hello", None)

# 空元组
empty_tuple = ()

# 单个元素的元组(注意末尾的逗号)
single_item_tuple = (5,)  # 没有逗号则只是括号中的数字

访问元组中的元素

和列表一样,元组的元素有索引(indexes)用于定位。Python使用从零开始的索引,第一个元素位于索引0。你可以像列表一样用方括号访问元素。

colors = ("red", "green", "blue")
print(colors[0])  # 输出:red
print(colors[2])  # 输出:blue

负索引同样有效,允许从元组末尾开始访问。

print(colors[-1])  # 输出:blue
print(colors[-2])  # 输出:green

为什么元组是不可变的?

元组创建后无法修改、添加或删除元素。尝试修改元组会导致错误:

colors = ("red", "green", "blue")
colors[1] = "yellow"  # 这会抛出TypeError错误:'tuple'对象不支持项赋值

这种不可变性使元组更适合存储不应意外更改的数据,例如坐标(coordinates)或固定参数(parameters)。

常见元组操作

虽然元组不可变,但仍可以执行一些操作:

  1. 合并(Concatenation):使用+运算符合并两个元组。
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple)  # 输出:(1, 2, 3, 4, 5, 6)
  1. 重复(Repetition):使用*运算符重复元组。
single_color = ("red",)
repeated_tuple = single_color * 3
print(repeated_tuple)  # 输出:('red', 'red', 'red')
  1. 检查元素存在:使用in关键字检查元素是否存在。
colors = ("red", "green", "blue")
print("green" in colors)  # 输出:True
print("yellow" in colors)  # 输出:False
  1. 元组长度:使用len()函数获取元素数量。
print(len(colors))  # 输出:3

元组方法

元组有两个主要方法:

  • count(value):返回某个值在元组中出现的次数。
numbers = (1, 2, 2, 3, 3, 3)
print(numbers.count(2))  # 输出:2
  • index(value):返回某个值首次出现的索引。
print(colors.index("green"))  # 输出:1

元组解包(Unpacking Tuples)

元组的一个强大功能是解包(unpacking),允许将元组的元素直接赋值给变量。

# 将元组解包到变量中
coordinates = (10, 20)
x, y = coordinates  # x变为10,y变为20
print(x, y)  # 输出:10 20

# 解包包含更多元素的元组
person = ("Alice", 30, "engineer")
name, age, job = person
print(name, age, job)  # 输出:Alice 30 engineer

元组 vs. 列表:何时使用?

特性

元组(Tuple)

列表(List)

可变性(Mutability)

不可变(Immutable)

可变(Mutable)

语法(Syntax)

使用()

使用[]

使用场景

存储固定数据(如配置信息)

存储可变数据(如动态列表)

性能(Performance)

遍历速度更快

稍慢

示例:使用元组存储记录

元组非常适合存储不应更改的记录,例如学生信息:

student = ("Bob", 18, "Math", 90.5)
# 解包元组以显示信息
name, age, subject, score = student
print(f"{name} is {age} years old, studying {subject} with a score of {score}.")
# 输出:Bob is 18 years old, studying Math with a score of 90.5.

专业词汇和不常用词汇表

tuple, /'tupl/ or /'tjupl/, 元组
immutable, /'mjutbl/, 不可变的
constant, /'kɑnstnt/, 恒定的
records, /'rekrdz/, 记录
coordinates, /ko'rdnts/, 坐标
parameters, /p'raemtrz/, 参数
concatenation, /knkaet'nen/, 合并
repetition, /rep'tn/, 重复
unpacking, /n'paek/, 解包
mutability, /mjut'blti/, 可变性
syntax, /'sntaeks/, 语法
performance, /pr'frmns/, 性能

原文链接:,转发请注明来源!