Chapter 9: Compound Data Types
In the programming world, data is never isolated. We not only deal with individual numbers or strings but also manage a collection of data, such as a list of student grades, a set of coordinate points, or a collection of user tags.
In Python, containers used to store multiple data items are called Compound Data Types. They allow us to efficiently organize, access, and manipulate batches of data, thereby constructing more complex program structures.
Learning Objectives:
(1) Understand the concept and function of compound data types.
(2) Master the creation, access, and manipulation methods of lists, tuples, and sets.
(3) Distinguish between mutable and immutable types and their usage scenarios.
(4) Utilize compound types for common tasks such as deduplication, statistics, and grouping.
(5) Master the structure and application scenarios of mapping structures (dictionaries).
9.1 Overview of Compound Data Types
Real-world problems often involve multiple sets of related data. For example:
“Student grades” is a set of scores;
“City temperatures” is a set of temperatures;
“AI model outputs” is a set of predicted values.
In such cases, we need a container that can hold multiple values in a single variable.
Python provides various compound data types (lists, tuples, sets, dictionaries, etc.) to accomplish this task. They not only store multi-element data but also allow flexible manipulation of these elements.
9.1.1 Mutable and Immutable
(1) Mutable Types
Content can be modified, such as lists, sets, dictionaries, etc.
(2) Immutable Types
Content is fixed, such as integers, ranges, strings, tuples, frozen sets, etc.
For example, the content of a list can be added or removed at any time, while once a tuple is created, its internal elements cannot be changed.
9.1.2 Ordered and Unordered
(1) Sequence Types
Elements can be accessed by position, are iterable, and support indexing and slicing. Such as lists, tuples, ranges, strings, byte types, etc.
(2) Unordered Types
Data is organized by content, elements are unique and do not support indexing. Such as sets, frozen sets, etc.
9.1.3 Mapping Types
Such as dictionaries, which store key-value pairs, where keys must be unique and hashable. Access is done through keys rather than indices.
9.2 List Type
Lists are one of the most flexible data structures in Python, capable of storing any number of elements in order and can be modified, added, or deleted at any time.
Lists are very suitable for storing serialized data, such as multiple image paths, model parameter sequences, experimental result records, etc.
9.2.1 Creating Lists
A list (list) object can be defined directly using square brackets [] or created from an iterable using the built-in constructor list().
It can contain elements of any type and supports nesting.
nums = [1, 2, 3, 4] # Directly using square brackets
words = list("hello") # Using list(). String → List ['h', 'e', 'l', 'l', 'o']
mixed = [1, "hello", 3.14, True] # Mixed types
empty = [] # Empty list
List comprehensions are a concise and efficient way to construct lists in a single line.
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
9.2.2 Common List Operations
Mastering these common operations can help you use lists more efficiently.
(1) Concatenation, Repetition, Membership Testing
a = [1, 2]
b = [3, 4]
print(a + b) # [1, 2, 3, 4], concatenation
print(a * 3) # [1, 2, 1, 2, 1, 2], repetition
print(2 in a) # True, using in and not in to check for element existence
(2) Indexing and Slicing
nums = [1, 2, 3, 4]
print(nums[0]) # First element 1
print(nums[-1]) # Last element 4
print(nums[1:3]) # Slice: from the 2nd to the 3rd element [2,3]
Tip:
The syntax for indexing and slicing in sequence types is similar to that of strings.
(3) Modification and Deletion
lst = [1, 2, 3, 4, 5]
lst[0] = 10 # Directly modify element
print(lst) # [10, 2, 3, 4, 5]
lst[1:3] = [20, 30] # Bulk replace elements
print(lst) # [10, 20, 30, 4, 5]
lst[2:4] = [] # Delete elements
print(lst) # [10, 20, 5]
del lst[1] # Delete element at index 1
print(lst) # [10, 5]
(4) Accessing and Unpacking
# Basic unpacking
a, b, c = [1, 2, 3]
print(a, c) # 1 3
# Variable unpacking with *
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last) # 1 [2, 3, 4] 5
# Using _ to ignore some values
name, _, score = ["Alice", "ID123", 95]
print(name, score) # Alice 95
(5) Iteration
fruits = ["apple", "banana", "cherry"]
for f in fruits: print(f)
# Iterating with index
for i, f in enumerate(fruits): print(i, f)
(6) Using Built-in Functions
Many built-in functions can be directly used on lists.
nums = [5, 2, 9, 1]
print(len(nums)) # 4, length
print(max(nums)) # 9, maximum value
print(min(nums)) # 1, minimum value
print(sum(nums)) # 17, sum
print(sorted(nums)) # [1, 2, 5, 9], returns a new list, original list unchanged
Example 9.2.1: Deduplication and Sorting of Lists
Convert to a set and then back to a list to achieve quick deduplication.
data = [5, 2, 3, 2, 5, 7]
clean_data = sorted(list(set(data)))
print("Cleaned data:", clean_data)
Note: This can be applied in data analysis scenarios for “removing duplicates”.
9.2.3 List Methods
In addition to common operators and built-in functions, Python also provides a rich set of class methods for list objects to achieve more granular operations.
(1) Adding and Inserting
fruits = ["apple", "banana"]
fruits.append("orange") # Add to the end
fruits.insert(1, "pear") # Insert at index
(2) Deleting and Clearing
fruits.remove("banana") # Remove specified element
fruits.pop() # Remove the last one
fruits.clear() # Clear the list
(3) Sorting and Reversing
nums = [3, 1, 4, 2]
nums.sort() # Ascending sort
nums.reverse() # Reverse order
(4) Copying and Nesting
a = [1, 2, 3]
b = a.copy() # Shallow copy
matrix = [[1, 2], [3, 4]] # Two-dimensional list
Note:
Python provides shallow copy and deep copy methods for copying objects.
Shallow Copy creates a new object, but the internal elements (sub-objects) are still references to the original object.Deep Copy creates a new object and recursively copies all internal sub-objects, forming a completely independent copy.
import copy
deep_copy = copy.deepcopy(matrix)
Note: Deep copy will recursively copy all levels of objects, suitable for nested lists and other structures.
These methods cover almost all common operations of list objects and are one of the most commonly used interfaces in data structures.
9.2.4 Comprehensive Examples and Applications of Lists
Example 9.2.2: Calculating the Average Brightness of Multiple Images
In image processing or machine learning tasks, it is often necessary to calculate the average brightness of multiple images to assess the exposure level of a dataset or perform normalization operations.
def average_brightness(brightness_values): return sum(brightness_values) / len(brightness_values)
brightness_list = [128, 145, 160, 150, 140]
avg = average_brightness(brightness_list)
print(f"Average Brightness: {avg:.1f}")
Note:
In AI image preprocessing, this method can be used to quickly calculate the average brightness of a sample set for data normalization or exposure compensation.
Example 9.2.3: Chinese Text Segmentation and Word Cloud Visualization
This example demonstrates how to use the jieba library for Chinese text segmentation, remove stop words, and then generate a word cloud using the WordCloud library to help visualize important vocabulary in the text.
Install dependencies:
pip install jieba wordcloud matplotlib
Example code:
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# NLP Musk's advice to young people
sentences = [ "Don't be afraid to take risks when you're young, and don't be afraid of failure.", "Spend your time on what really matters, not on meaningless consumption.", "Strive to be with smart, hardworking, and willing-to-invest people.", "Do what you truly believe in, and don't be swayed by others' expectations.", "Continuous learning and growth are much more important than whether you are a genius."]
# Simple stop words
stopwords = ["的", "在", "不是", "也", "而", "是否"]
tokenized = [] # To store the segmentation results of each sentence (list of lists)
for text in sentences:
# 1. Chinese segmentation (jieba.cut returns an iterable, needs to be converted to list)
words = list(jieba.cut(text))
# 2. Remove stop words + punctuation
cleaned = [ w for w in words if w not in stopwords and w.strip() not in ",。!?、“”" ]
tokenized.append(cleaned) # Add each sentence's segmentation list to the total result
# Output segmentation results sentence by sentence
print("Segmentation results (after removing stop words):")
for i, lst in enumerate(tokenized, 1): print(i, lst)
# 3. Flatten all words, prepare for word cloud
all_words = [w for lst in tokenized for w in lst]
# Create word cloud object
wc = WordCloud( font_path="msyh.ttc", # Common font under Windows (to ensure support for Chinese)
width=800, height=400, background_color="white")
# Generate word cloud
wordcloud = wc.generate(" ".join(all_words)) # Word cloud needs a space-separated string
# Save word cloud image
wordcloud.to_file("musk_advice_wordcloud.png")
print("\nWord cloud saved as musk_advice_wordcloud.png")
# ---- Immediately display the word cloud ----
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
Note:
In natural language processing (NLP), Chinese text segmentation is one of the fundamental tasks. By segmenting the text, we can extract meaningful words and further analyze important content in the text. Word clouds are a common method for visualizing text data, helping us intuitively discover keywords in the text through the visualization of word frequency.
📘 Summary
This lesson introduced the most flexible container type in Python—lists (list), covering the creation methods, common operations, built-in functions, and method calls, and understanding the application value of lists in data cleaning and AI preprocessing tasks through examples.
In the next lesson, we will continue to learn about tuples (tuple) and sets (set), one emphasizing “immutable order” and the other pursuing “uniqueness and set operations,” together forming the core system of Python’s compound data structures.
“Likes have good intentions, appreciation is encouragement”