9.3 Tuple Type
A tuple (tuple) is very similar to a list and is also an ordered sequence type, but the biggest difference is that tuples are immutable objects. Once created, their elements cannot be modified. The immutable nature of tuples makes them particularly suitable for applications that require traceable history, such as recording versions, log snapshots, or original model parameters..
9.3.1 Creating Tuples
Tuples can be created by separating elements with commas , and are generally enclosed in parentheses (). They can also be created using the built-in function tuple().
t1 = 1, 2, 3
t2 = (1, 2, 3)
t3 = tuple(["a", "b", "c"]) # List → Tuple
t4 = () # Empty Tuple
print(t1, t2, t3, t4)
If it contains only one element, a comma , must be added; otherwise, it will not be recognized as a tuple:
single = (5,) # Correct
not_tuple = (5) # Actually an int
print(type(single), type(not_tuple))
Tuples also support nested structures:
nested = (1, (2, 3), 4)
9.3.2 Common Operations on Tuples
Tuples are very similar to lists and are also an ordered sequence type, thus sharing most sequence operations.
(1) Sequence Operations (Concatenation, Repetition, and Comparison)
a = (1, 2)
b = (3, 4)
print(a + b) # (1, 2, 3, 4)
print(a * 2) # (1, 2, 1, 2)
# Compare element by element
print((1, 2) < (1, 3)) # True
print((1, 2, 3) > (1, 2)) # True
(2) General Sequence Operations (Indexing, Slicing, Iteration, and Membership Testing)
t = (10, 20, 30, 40)
# Indexing
print(t[0]) # 10
print(t[-1]) # 40
# Slicing
print(t[1:3]) # (20, 30)
# Create a new tuple by slicing
modified = t[:2] + t[3:] # (10, 20, 40)
# Iteration
for value in t: print(value)
# Membership Testing
print(20 in t) # True
print(50 not in t) # True
(3) Using Built-in Functions and Tuple Methods
t1 = (5, 2, 9, 1)
print(len(t1)) # 4 Get the length of the tuple
print(max(t1)) # 9 Get the maximum value
print(min(t1)) # 1 Get the minimum value
print(sum(t1)) # 17 Sum of all elements
print(sorted(t1)) # [1, 2, 5, 9] Sort, note that sorted() returns a list
# If a tuple is needed, use tuple(sorted(t1))
# enumerate() returns a result where each element is a tuple of (index, value)
fruits = ("apple", "banana", "cherry")
for i, fruit in enumerate(fruits): print(i, fruit)
# zip() can pair two sequences
names = ['Ai Wanting', 'Ju Zizhou', 'Yue Lushan']
scores = [95, 85, 98]
zipped = list(zip(names, scores)) print(zipped) # [('Ai Wanting', 95), ('Ju Zizhou', 85), ('Yue Lushan', 98)]
# Using * operator can unpack zipped data
names, scores = zip(*zipped) print(names) # ('Ai Wanting', 'Ju Zizhou', 'Yue Lushan')
print(scores) # (95, 85, 98)
# Tuple class methods
t2 = (1, 2, 3, 2, 4, 5)
count = t2.count(2) # 2 Count occurrences of an element
position = t2.index(2) # 1 Return the index of the first occurrence of an element
print(t2.index(2, 2)) # 3 Continue searching after index 2
(4) Modifying Mutable Object Elements in Tuples
Although tuples themselves are immutable, if they contain mutable objects (like lists), the internal data can still be modified.
t = (1, [2, 3])
t[1][0] = 99
print(t) # (1, [99, 3])
Note: This does not violate the immutability of tuples because what is changed is the mutable object itself, not the binding relationship of the tuple.
(5) Application of Tuples in Function Design
Tuples are often used as return values for functions, allowing a function to return multiple results at once.
def calc_stats(numbers): return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = calc_stats([10, 20, 30, 40])
print(low, high, avg) # 10 40 25.0
Note: Python functions always return a single object. When written as “return a, b”, it actually returns a tuple.
In the function’s actual parameters, the * operator can be used for positional argument unpacking:
def add(x, y): return x + y
args = (3, 5)
print(add(*args)) # Equivalent to add(3, 5)
In the function’s formal parameters, the * operator can be used to capture variable positional arguments.
def avg(*args): # Formal parameter args is a tuple return sum(args) / len(args)
print(avg(1, 2, 3, 4))
9.3.3 Examples and Applications of Tuples
Example 9.3.1: AI Model Parameter Comparison (Weight Freezing Example)
During the fine-tuning process of deep learning models, some pre-trained parameters are usually fixed while other layers are updated. Tuples can be used to store “frozen parameters” to prevent accidental modification.
# Fix model weights
base_weights = (0.5, 0.8, 0.9)
def compare_weights(new_weights): for i in range(len(base_weights)): diff = new_weights[i] - base_weights[i] print(f"Parameter {i+1} change: {diff:+.2f}")
compare_weights((0.55, 0.75, 0.95))
Note:
The immutability of tuples ensures the safety of key parameters in models and is often used to record original weights in AI model fine-tuning or version management.
Example 9.3.2 Coordinate Transformation
The following example can translate and scale multiple coordinate points.
def coordinate_transform(*points, scale=1.0, offset=(0, 0)): transformed_points = [] for point in points: if len(point) == 2: # 2D point x, y = point new_x = (x + offset[0]) * scale new_y = (y + offset[1]) * scale transformed_points.append((new_x, new_y))
# Return all transformed points, can be unpacked
return tuple(transformed_points)
# Usage example
p1, p2, p3 = (1, 2), (3, 4), (5, 6)
scaled_points = coordinate_transform(p1, p2, p3, scale=2.0, offset=(1, 1))
print(f"Transformed points: {scaled_points}")
Output:
Transformed points: ((4.0, 6.0), (8.0, 10.0), (12.0, 14.0))
9.4 Set Type
A set (set) is an unordered, mutable, and unique sequence type. Elements in a set must be hashable, meaning they cannot include mutable types like lists or dictionaries.
Sets are commonly used for deduplication, membership testing, and mathematical set operations (intersection, union, difference, etc.).
9.4.1 Creating Sets
Sets can be created using curly braces {} or the built-in function set().
An empty set must use set(); otherwise, {} will be recognized as a dictionary.
s1 = {1, 2, 3, 4}
s2 = set([2, 3, 5])
print(s1, s2)
empty = set()
print(type(empty)) # <class 'set'>
Sets can also be created using comprehensions.
squares = {x**2 for x in range(-3, 4)}
print(squares) # For example, -3 and 3 have the same square, so they are automatically deduplicated.
Note that the output order of sets is not fixed and may differ each time it runs.
9.4.2 Set Operations
Sets support a rich set of operators for implementing mathematical set operations.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Union: {1, 2, 3, 4, 5}
print(A & B) # Intersection: {3}
print(A - B) # Difference: {1, 2}
print(A ^ B) # Symmetric Difference: {1, 2, 4, 5}
These operations can also be implemented using corresponding methods:
print(A.union(B))
print(A.intersection(B))
print(A.difference(B))
print(A.symmetric_difference(B))
9.4.3 Common Operations on Sets
In addition to the above set operations, sets also support common operations such as membership testing, iteration, and using built-in functions, similar to other mutable sequences. However, due to sets being stored based on hash tables and having no fixed order, indexing and slicing cannot be used.
Elements can also be added or removed, and relationship tests can be performed using set methods.
(1) Adding and Removing Elements
fruits = {"apple", "banana"}
fruits.add("cherry") # Add a single element
fruits.update(["orange", "pear"]) # Add multiple elements (iterable)
print(fruits)
fruits.remove("banana") # Remove specified element, raises error if not found
fruits.discard("grape") # Remove element, does not raise error if not found
fruits.clear() # Clear the set
(2) Relationship Testing
A = {1, 2}
B = {1, 2, 3}
print(A <= B) # True, subset test
print(B > A) # True, superset test
print(A.isdisjoint({4, 5})) # True, no intersection
Sets are implemented based on hash tables, with an average time complexity of O(1) for membership testing, adding, and removing.
9.4.4 Examples and Applications of Sets
Example 9.4.1: Data Deduplication and Statistics
Sets can quickly implement deduplication operations.
The following example demonstrates how to remove duplicate user IDs and calculate the unique count.
users = ["A12", "B09", "A12", "C33", "B09", "D20"]
unique_users = set(users)
print("Unique user count:", len(unique_users))
print("User set:", unique_users)
Note: The uniqueness of sets makes them an efficient tool for “deduplication” in data analysis.
Example 9.4.2: User Interest Intersection Recommendation
In recommendation systems, sets can be used to quickly find common interests among different users, thus generating personalized recommendation content.
user_A = {"AI", "Python", "Data"}
user_B = {"AI", "Music", "Data"}
common = user_A & user_B
print("Common interests:", common)
Note: Set operations can efficiently achieve interest tag matching, which is one of the core logics in social recommendation and content recommendation algorithms.
📘 Summary
This lesson introduced two important composite data types: tuples (tuple) and sets (set). Tuples are ordered and immutable sequences, suitable for storing fixed structures or data that should not be modified; sets are unordered containers with unique elements, commonly used for deduplication, set operations, and quick relationship testing.
In the next lesson, we will learn about mapping types—dictionaries (dict), which store and access data through a “key-value” structure, making it one of the core and most powerful data types in Python.
“Likes are beautiful, appreciation is encouragement”