I. What Is a Tuple
A tuple is a built-in sequence type provided by Python, used to store multiple elements in a fixed order.
Tuples are very similar to lists. Both support indexing, slicing, iteration, and membership testing, but the most important difference between the two is:
- Lists are mutable sequences, and their elements can be modified after creation.
- Tuples are immutable sequences, and the references of their elements cannot be changed after creation.
Example:
# Create a list
numbers_list = [10, 20, 30]
# Create a tuple
numbers_tuple = (10, 20, 30)
print(numbers_list)
# [10, 20, 30]
print(numbers_tuple)
# (10, 20, 30)
Tuples are suitable for representing a set of data with a fixed structure, such as:
- Geographic coordinates: longitude and latitude.
- RGB color: the red, green, and blue components.
- A row returned by a database query.
- Multiple results returned by a function.
- Configuration items in a fixed format.
- Structured data that is not intended to be reassigned.
1. Main Characteristics of Tuples
| Feature | Description |
|---|---|
| Ordered | Elements are arranged in a definite order |
| Indexable | Supports positive and negative indexing |
| Slicing | Supports slicing operations |
| Immutability | Elements in a tuple cannot be replaced, added, or removed |
| Duplicates | Duplicate elements are allowed |
| Mixed types | Can store data of different types |
| Nestable | Can contain other tuples, lists, and dictionaries |
| Iterable | Supports traversal with a for loop |
| Hashability | Can be used as a dictionary key or set element when the conditions are met |
Note: A tuple being immutable does not mean that all objects it contains are immutable. If a tuple references mutable objects such as lists, those objects can still be modified.
2. Differences Between Tuples and Lists
| Comparison aspect | Tuple | List |
|---|---|---|
| Definition symbols | () |
[] |
| Ordered | Yes | Yes |
| Mutable | No | Yes |
| Supports indexing | Yes | Yes |
| Supports slicing | Yes | Yes |
| Allows duplicate elements | Yes | Yes |
| Allows mixed types | Yes | Yes |
| Supports adding elements | No | Yes |
| Supports removing elements | No | Yes |
| Supports in-place sorting | No | Yes |
| Can be used as a dictionary key | Yes, when it satisfies the hashable conditions | No |
Example:
# Lists can be modified
numbers = [1, 2, 3]
numbers[0] = 100
print(numbers)
# [100, 2, 3]
# Tuples cannot be modified
values = (1, 2, 3)
# values[0] = 100
# TypeError: 'tuple' object does not support item assignment
II. Ways to Create Tuples
Python provides several ways to create a tuple, and the most important one is to separate elements with commas.
1. Create a Tuple with Parentheses
The most common way to create one is to use parentheses:
numbers = (10, 20, 30)
print(numbers)
# (10, 20, 30)
print(type(numbers))
# <class 'tuple'>
Parentheses help make the tuple structure explicit and improve code readability.
2. Create a Tuple with Commas
Pay special attention: what actually creates a tuple is the comma, not the parentheses.
numbers = 10, 20, 30
print(numbers)
# (10, 20, 30)
print(type(numbers))
# <class 'tuple'>
Therefore, both of the following forms can create a tuple:
a = (1, 2, 3)
b = 1, 2, 3
print(type(a))
# <class 'tuple'>
print(type(b))
# <class 'tuple'>
3. Create an Empty Tuple
An empty tuple contains no elements.
empty_tuple = ()
print(empty_tuple)
# ()
print(type(empty_tuple))
# <class 'tuple'>
You can also create one with tuple():
empty_tuple = tuple()
print(empty_tuple)
# ()
4. Creating a Tuple with Only One Element
Single-element tuples are where beginners most often make mistakes.
a = (10)
print(a)
# 10
print(type(a))
# <class 'int'>
Here, (10) is just an integer expression wrapped in parentheses, not a tuple.
The correct way:
a = (10,)
print(a)
# (10,)
print(type(a))
# <class 'tuple'>
You can also do it without parentheses:
a = 10,
print(type(a))
# <class 'tuple'>
The key is that the trailing comma must be kept.
5. Using tuple() to Convert Iterables
tuple() is a Python built-in type constructor that converts an iterable into a tuple.
# List to tuple
numbers = [1, 2, 3]
result = tuple(numbers)
print(result)
# (1, 2, 3)
# String to tuple
text = "Python"
result = tuple(text)
print(result)
# ('P', 'y', 't', 'h', 'o', 'n')
# range to tuple
result = tuple(range(5))
print(result)
# (0, 1, 2, 3, 4)
If the object passed in is already a tuple, tuple() usually returns that tuple directly instead of creating a new copy of it.
numbers = (1, 2, 3)
result = tuple(numbers)
print(result)
# (1, 2, 3)
print(result is numbers)
# True
Don't rely on tuple() to copy a tuple. Tuples themselves are immutable, and there is usually no need to copy one.
6. Comparison of Different Creation Methods
| Creation Method | Example | Result |
|---|---|---|
| Parentheses | (1, 2, 3) |
Tuple |
| Comma-separated | 1, 2, 3 |
Tuple |
| Single element | (1,) |
Single-element tuple |
| Empty tuple | () |
Empty tuple |
| Constructor | tuple([1, 2]) |
Tuple |
| Iterable conversion | tuple("abc") |
Tuple of characters |
III. Accessing Tuple Elements
A tuple is an ordered sequence, and its elements can be accessed by index.
1. Forward Indexing
Forward indexing starts at 0.
colors = ("red", "green", "blue")
print(colors[0])
# red
print(colors[1])
# green
print(colors[2])
# blue
The correspondence between indices and element positions:
| Index | Element |
|---|---|
0 |
"red" |
1 |
"green" |
2 |
"blue" |
2. Negative Indexing
Negative indexing starts at -1, meaning access from right to left.
colors = ("red", "green", "blue")
print(colors[-1])
# blue
print(colors[-2])
# green
print(colors[-3])
# red
The correspondence between forward and negative indices:
| Forward Index | Negative Index | Element |
|---|---|---|
0 |
-3 |
red |
1 |
-2 |
green |
2 |
-1 |
blue |
3. Using len() to Get the Length of a Tuple
len() is used to get the number of elements in a tuple.
numbers = (10, 20, 30, 40)
print(len(numbers))
# 4
The length of an empty tuple is 0:
empty = ()
print(len(empty))
# 0
4. Index Out of Range
When the index you access is beyond the range of the tuple, an IndexError is raised.
numbers = (10, 20, 30)
# print(numbers[3])
# IndexError: tuple index out of range
You can check the length before accessing:
index = 3
if 0 <= index < len(numbers):
print(numbers[index])
else:
print("索引超出范围")
If you need to access from the end, you should also consider the range of negative indices:
index = -1
if -len(numbers) <= index < len(numbers):
print(numbers[index])
5. Accessing Nested Tuples with Indices
Tuples can contain other tuples, forming a nested structure.
data = (
("Alice", 20),
("Bob", 25),
("Cindy", 30)
)
print(data[0])
# ('Alice', 20)
print(data[0][0])
# Alice
print(data[1][1])
# 25
When accessing a nested tuple, each level of index corresponds to one container.
IV. Tuple Slicing
Tuples support slicing, which lets you get a consecutive or spaced-out segment of elements.
Slicing does not modify the original tuple; it returns a new tuple.
1. Basic Slicing Syntax
tuple[start:stop:step]
Parameter meanings:
start: the starting position, inclusive of that index.stop: the ending position, exclusive of that index.step: the step size, defaults to1.
2. Getting Part of the Elements
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
# (20, 30, 40)
The slice's ending position is not included in the result.
3. Omitting the Start Index
numbers = (10, 20, 30, 40, 50)
print(numbers[:3])
# (10, 20, 30)
This means taking elements from the beginning up to, but not including, index 3.
4. Omitting the End Index
numbers = (10, 20, 30, 40, 50)
print(numbers[2:])
# (30, 40, 50)
This means taking elements from index 2 to the end.
5. Specifying a Step
numbers = (10, 20, 30, 40, 50, 60)
print(numbers[::2])
# (10, 30, 50)
print(numbers[1::2])
# (20, 40, 60)
A step of 2 means taking every other element.
6. Reverse Slicing
You can retrieve elements in reverse by using a negative step.
numbers = (10, 20, 30, 40, 50)
print(numbers[::-1])
# (50, 40, 30, 20, 10)
Reverse slicing with a specified range:
numbers = (10, 20, 30, 40, 50, 60)
print(numbers[4:1:-1])
# (50, 40, 30)
Note that with a negative step, the slice's start position usually needs to be greater than the end position.
7. Slicing Does Not Modify the Original Tuple
numbers = (10, 20, 30, 40, 50)
result = numbers[1:4]
print(result)
# (20, 30, 40)
print(numbers)
# (10, 20, 30, 40, 50)
8. Out-of-Range Slicing Does Not Raise IndexError
Unlike accessing a single index, when a slice's bounds exceed the range, it is usually truncated automatically to the valid range.
numbers = (10, 20, 30)
print(numbers[0:100])
# (10, 20, 30)
print(numbers[100:200])
# ()
print(numbers[-100:2])
# (10, 20)
9. Common Uses of Tuple Slicing
| Use case | Example |
|---|---|
| Get the first few elements | data[:3] |
| Get the last few elements | data[-3:] |
| Skip the first element | data[1:] |
| Take every other element | data[::2] |
| Reverse the order | data[::-1] |
| Get a middle range | data[2:5] |
V. Iterating Over Tuples
A tuple is an iterable object, and you can iterate over its elements in several ways.
1. Iterating with a for loop
colors = ("red", "green", "blue")
for color in colors:
print(color)
Output:
red
green
blue
This is the most common way to iterate over a tuple.
2. Iterating with an index
colors = ("red", "green", "blue")
for index in range(len(colors)):
print(index, colors[index])
Output:
0 red
1 green
2 blue
This approach suits situations where you need both the element's position and its value.
3. Using enumerate() to get the index and value
enumerate() lets you get both the index and the element while iterating.
colors = ("red", "green", "blue")
for index, color in enumerate(colors):
print(index, color)
Specify a starting index:
colors = ("red", "green", "blue")
for index, color in enumerate(colors, start=1):
print(index, color)
Output:
1 red
2 green
3 blue
4. Iterating over nested tuples
students = (
("Alice", 90),
("Bob", 85),
("Cindy", 95)
)
for student in students:
name, score = student
print(name, score)
You can also unpack directly:
for name, score in students:
print(name, score)
5. Iterating with a while loop
numbers = (10, 20, 30, 40)
index = 0
while index < len(numbers):
print(numbers[index])
index += 1
For ordinary iteration, for is usually preferable: the code is more concise, and you are less likely to run into index-out-of-range problems.
VI. Tuple Unpacking
Tuple unpacking is one of the most important and most useful features of Python tuples.
It lets you assign the multiple elements of a tuple to multiple variables separately.
1. Basic unpacking
person = ("Alice", 25)
name, age = person
print(name)
# Alice
print(age)
# 25
During unpacking, the number of variables on the left must match the number of unpackable elements on the right.
2. Mismatched unpacking counts
data = (10, 20, 30)
# a, b = data
# ValueError: too many values to unpack
# a, b, c, d = data
# ValueError: not enough values to unpack
If you need to receive an uncertain number of elements, you can use a starred expression.
3. Using * to receive multiple elements
numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)
# 10
print(middle)
# [20, 30, 40]
print(last)
# 50
Note: the result collected by the starred variable is a list, not a tuple.
It can also be placed in other positions:
numbers = (10, 20, 30, 40, 50)
*start, last = numbers
print(start)
# [10, 20, 30, 40]
print(last)
# 50
numbers = (10, 20, 30, 40, 50)
first, *rest = numbers
print(first)
# 10
print(rest)
# [20, 30, 40, 50]
Only one starred target is allowed in an unpacking expression.
4. Nested unpacking
If a tuple contains other tuples, nested unpacking can be used.
student = (
"Alice",
(20, "Computer Science")
)
name, (age, major) = student
print(name)
# Alice
print(age)
# 20
print(major)
# Computer Science
5. Swapping variables
Python can use tuple packing and unpacking to swap variables.
a = 10
b = 20
a, b = b, a
print(a)
# 20
print(b)
# 10
This approach does not require creating an extra temporary variable.
6. Functions returning multiple values
A Python function can return multiple results through a comma-separated return expression.
def get_user():
return "Alice", 25, "Developer"
user = get_user()
print(user)
# ('Alice', 25, 'Developer')
name, age, job = get_user()
print(name)
# Alice
Semantically, multiple return values are actually packed into a tuple.
7. Practical applications of unpacking
Database query results often come in the form of tuples.
users = [
(1, "Alice", 25),
(2, "Bob", 30),
(3, "Cindy", 28)
]
for user_id, name, age in users:
print(user_id, name, age)
This approach can make the data structure clearer.
VII. Tuple concatenation and repetition
Although tuples are immutable, they support creating new tuples.
1. Concatenating tuples with +
+ can concatenate two tuples into a new tuple.
a = (1, 2, 3)
b = (4, 5, 6)
result = a + b
print(result)
# (1, 2, 3, 4, 5, 6)
The original tuples are not changed:
print(a)
# (1, 2, 3)
print(b)
# (4, 5, 6)
2. Repeating tuples with *
* can repeat the contents of a tuple a specified number of times.
numbers = (1, 2, 3)
result = numbers * 3
print(result)
# (1, 2, 3, 1, 2, 3, 1, 2, 3)
When the repetition count is 0 or negative, the result is an empty tuple:
numbers = (1, 2, 3)
print(numbers * 0)
# ()
print(numbers * -1)
# ()
3. Both concatenation and repetition produce new tuples
a = (1, 2)
b = a + (3,)
print(a)
# (1, 2)
print(b)
# (1, 2, 3)
print(a is b)
# False
Note that concatenation and repetition only create a new outer tuple. If it contains mutable objects internally, those inner objects may still be shared by multiple tuples.
VIII. Tuple membership testing and comparison
Tuples support membership testing, equality comparison, and ordering comparison.
1. Using in to check whether an element exists
colors = ("red", "green", "blue")
print("red" in colors)
# True
print("yellow" in colors)
# False
Use not in to check whether an element is absent:
print("yellow" not in colors)
# True
Membership testing usually requires checking elements one by one, with a time complexity of O(n).
2. Using == to check whether tuples are equal
Two tuples compare as equal only when they have the same length and all elements at corresponding positions are equal.
a = (1, 2, 3)
b = (1, 2, 3)
c = (3, 2, 1)
print(a == b)
# True
print(a == c)
# False
Tuple comparison takes element order into account.
3. Using < and > for ordering comparisons
Tuples support lexicographical comparison.
The comparison process:
- Start comparing from the first position.
- Find the first pair of elements that are not equal.
- The result of comparing that pair determines the overall result.
- If all preceding elements are equal, the result is then determined by length.
a = (1, 2, 3)
b = (1, 2, 4)
print(a < b)
# True
The first element is equal, the second element is also equal, and the third element 3 is less than 4, so a < b.
Let's look at another example:
a = (1, 5, 9)
b = (2, 0, 0)
print(a < b)
# True
Since the first element 1 is less than 2, the subsequent elements no longer participate in determining the result.
4. Type Issues in Tuple Comparison
Elements of different types in a tuple cannot necessarily be compared by magnitude.
a = (1, "Python")
b = (2, "Java")
print(a < b)
# True
Here the first element has already determined the comparison result, so the strings are not compared.
But if the first position is equal:
a = (1, "Python")
b = (1, "Java")
# print(a < b)
# The result depends on the string comparison rules; the comparison works normally
For type combinations that cannot be compared by magnitude, Python raises a TypeError.
a = (1, None)
b = (1, 2)
# print(a < b)
# TypeError
Therefore, tuple sorting and magnitude comparison require that the corresponding elements being compared have compatible comparison semantics.
IX. Why Tuples Are Immutable
Immutability is the most central design feature of tuples.
Understanding it requires looking at it from two angles: object references and container structure.
1. Tuples Do Not Allow Replacing Elements
numbers = (10, 20, 30)
# numbers[0] = 100
# TypeError
You cannot modify elements in a tuple directly through an index.
2. Tuples Do Not Support Adding Elements
numbers = (10, 20, 30)
# numbers.append(40)
# AttributeError
Tuples do not have list modification methods such as append(), extend(), and insert().
3. Tuples Do Not Support Deleting Elements
numbers = (10, 20, 30)
# del numbers[0]
# TypeError
Nor can you delete elements in them via remove() or pop().
4. Variables Can Be Rebound
Although the tuple object itself cannot be modified, you can make a variable point to another tuple.
numbers = (1, 2, 3)
numbers = (4, 5, 6)
print(numbers)
# (4, 5, 6)
This is not modifying the original tuple but creating another tuple and rebinding the variable numbers to the new object.
5. The Difference Between Immutable Containers and Variable Binding
numbers = (1, 2, 3)
alias = numbers
numbers = (4, 5, 6)
print(numbers)
# (4, 5, 6)
print(alias)
# (1, 2, 3)
Rebinding a variable does not change the original tuple, nor does it affect other variables that still reference the original tuple.
6. A Tuple's Immutability Is a Shallow Structural Constraint
This is a very important point for understanding tuples.
A tuple cannot change the element references it holds, but the objects those references point to may be mutable objects.
data = ([1, 2], [3, 4])
data[0].append(100)
print(data)
# ([1, 2, 100], [3, 4])
What happened here?
- The first element of the tuple still references the original list.
- The second element of the tuple still references the original list.
- The contents inside the first list changed.
- The tuple's own element references did not change.
You can understand it with the following structure:
data
|
v
+----------------------+
| tuple |
| |
| [0] ----------+ |
| [1] -------+ | |
+------------|--|------+
| |
v v
list A list B
[1,2] [3,4]
A tuple being immutable means the tuple's own structure is immutable, not that every object inside it is immutable.
7. Truly Immutable Data Combinations
If you want the data in a tuple to be as immutable as possible, avoid putting mutable objects such as lists and dictionaries into it.
# All internal objects are immutable
data = (
100,
"Python",
(1, 2, 3),
frozenset({1, 2, 3})
)
This kind of structure is better suited to representing fixed data states.
10. Tuples and the Hashing Mechanism
Tuples have an important property: when they meet the conditions, they can be used as dictionary keys or set elements.
1. Tuples Can Be Used as Dictionary Keys
locations = {
(116.4074, 39.9042): "Beijing",
(121.4737, 31.2304): "Shanghai"
}
print(locations[(116.4074, 39.9042)])
# Beijing
This kind of structure is suitable for using coordinates, composite identifiers, and the like as dictionary keys.
2. Tuples Can Be Used as Set Elements
points = {
(1, 2),
(3, 4),
(5, 6)
}
print(points)
Elements in a set must be hashable objects.
3. Tuples Are Not Necessarily Hashable
If all elements in a tuple are hashable, then the tuple is usually hashable as well.
If a tuple contains unhashable objects such as lists or dictionaries, it cannot be used as a dictionary key or a set element.
a = (1, 2, 3)
print(hash(a))
# Can be computed normally
A tuple containing a list:
b = (1, [2, 3])
# print(hash(b))
# TypeError: unhashable type: 'list'
A tuple containing a dictionary has the same problem:
data = (1, {"name": "Alice"})
# print(hash(data))
# TypeError
4. Why Hashing Requires Stability
Dictionaries and sets rely on hash values to locate elements.
If an object's hash value changes while it is being used as a key, the data structure may not be able to locate it correctly.
Therefore, hashable objects need to satisfy a stable hash and equality contract.
A tuple itself is immutable, but if the internal objects it references are mutable, the entire tuple cannot simply be guaranteed to be hashable.
5. Use Cases for Tuples as Dictionary Keys
For example, using coordinates as grid positions:
grid = {}
grid[(0, 0)] = "起点"
grid[(1, 0)] = "道路"
grid[(1, 1)] = "终点"
print(grid[(1, 1)])
# End point
Multiple fields can also be combined into a composite key:
cache = {}
cache[("user_001", "profile")] = {
"name": "Alice",
"age": 25
}
As long as all elements in the tuple are hashable, it can be used as a dictionary key.
11. Common Tuple Methods and Built-in Functions
A tuple is an immutable sequence, so it provides fewer methods than a list.
1. count(): Count Occurrences of an Element
count() is used to count how many times a given element appears in a tuple.
numbers = (1, 2, 2, 3, 2, 4)
print(numbers.count(2))
# 3
print(numbers.count(100))
# 0
If the element does not exist, it returns 0 and does not raise an exception.
2. index(): Find the Position of an Element
index() returns the index of the first occurrence of an element.
numbers = (10, 20, 30, 20, 40)
print(numbers.index(20))
# 1
You can specify a search range:
numbers = (10, 20, 30, 20, 40)
print(numbers.index(20, 2))
# 3
If the element does not exist, a ValueError is raised.
3. The Two Main Tuple Methods
| Method | Description | Return Value |
|---|---|---|
count(value) |
Count occurrences of an element | Integer |
index(value) |
Find the index of the first occurrence of an element | Integer |
Tuples do not have list modification methods such as append(), extend(), remove(), pop(), sort(), and reverse().
4. Common Built-in Functions
Tuples can work with Python built-in functions to perform various operations.
| Function | Purpose | Example |
|---|---|---|
len() |
Get the number of elements | len(data) |
max() |
Get the maximum value | max(data) |
min() |
Get the minimum value | min(data) |
sum() |
Calculate the sum of the values | sum(data) |
sorted() |
Sort and return a list | sorted(data) |
any() |
Check whether any element is truthy | any(data) |
all() |
Check whether all elements are true | all(data) |
enumerate() |
Get the index and value | enumerate(data) |
reversed() |
Get a reverse iterator | reversed(data) |
tuple() |
Create or convert to a tuple | tuple(data) |
Example:
numbers = (10, 20, 30, 40)
print(len(numbers))
# 4
print(max(numbers))
# 40
print(min(numbers))
# 10
print(sum(numbers))
# 100
print(sorted(numbers, reverse=True))
# [40, 30, 20, 10]
Note: sorted() returns a list, not a tuple.
If you need to still get a tuple after sorting, you can convert it again:
numbers = (30, 10, 20)
result = tuple(sorted(numbers))
print(result)
# (10, 20, 30)
However, this creates a new tuple rather than modifying the original one.
12. Typical Use Cases for Tuples
Tuples are suitable for representing data with a fixed structure, a clear order, and usually no need for in-place modification.
1. Representing Coordinates
Coordinates usually consist of a fixed number of numeric values.
point = (116.4074, 39.9042)
longitude, latitude = point
print(longitude)
# 116.4074
print(latitude)
# 39.9042