22. Kiểu dữ liệu Set
Ở các bài trước, chúng ta đã học về kiểu dữ liệu List (danh sách), kiểu Tuple (bộ) và kiểu Dictionary (từ điển). Bài học này, chúng ta sẽ tìm hiểu về một kiểu dữ liệu nữa, đó là kiểu Set (tập hợp).
22.1 Kiểu dữ liệu Set là gì?
Hãy tưởng tượng, bạn có một chiếc túi đựng các viên bi màu. Trong chiếc túi này:
- Bạn không quan tâm viên bi nào được bỏ vào trước, viên bi nào được bỏ vào sau (không có thứ tự)
- Nếu bạn bỏ hai viên bi màu xanh giống hệt nhau vào, chiếc túi sẽ tự hiểu là chỉ có một viên bi màu xanh (không chứa phần tử trùng lặp)
Trên đây là 2 đặc điểm quan trọng của kiểu dữ liệu Set.
Trong Python, Set được định nghĩa bằng cặp ngoặc nhọn { }, các phần tử cách nhau bởi dấu phẩy.
Ví dụ:
# Khai báo một Set các môn học
mon_hoc = {"Toan", "Van", "Anh", "Toan"}
print(mon_hoc)
# Kết quả: {'Toan', 'Anh', 'Van'} (Lưu ý: Chữ "Toan" trùng lặp đã bị loại bỏ)
22.2 Truy cập các phần tử trong Set
Vì Set không có thứ tự, nên các phần tử không có số chỉ mục (index) như List. Bạn không thể dùng mon_hoc[0] để lấy phần tử đầu tiên.
Để xem một phần tử có nằm trong Set hay không, chúng ta dùng từ khóa in.
Ví dụ:
mon_hoc = {"Toan", "Van", "Anh"}
print("Toan" in mon_hoc)
# Kết quả: True
22.3 Thêm phần tử vào Set
Để thêm một phần tử vào Set, chúng ta có thể dùng 2 cách sau:
- add(): Thêm một phần tử
- update(): Thêm nhiều phần tử từ một List hoặc Set khác
Ví dụ:
trai_cay = {"Tao", "Cam"}
trai_cay.add("Xoai") # Thêm 1 quả
trai_cay.update(["Man", "Dao"]) # Thêm nhiều quả
print(trai_cay)
22.4 Xóa phần tử khỏi Set
Bạn có thể lấy phần tử ra khỏi Set bằng 3 cách:
- remove(): Xóa phần tử cụ thể. Nếu phần tử không tồn tại, chương trình sẽ báo lỗi
Ví dụ:
trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}
# 1. Xóa phần tử có tồn tại trong Set
trai_cay.remove("Cam")
print("Set sau khi xoa 'Cam':", hoa_qua)
# Kết quả: {'Tao', 'Xoai', 'Chuoi'}
# 2. Xóa phần tử KHÔNG tồn tại trong Set (sẽ phát sinh lỗi KeyError)
try: trai_cay.remove("Dua hau")
except KeyError as e: print(f"Lỗi xảy ra: Không tìm thấy phần tử {e} để xóa!")
- discard(): Xóa phần tử cụ thể. Nếu phần tử không tồn tại, chương trình không báo lỗi
- clear(): Xóa sạch toàn bộ các phần tử trong Set
Ví dụ:
trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}
trai_cay.clear()
print(trai_cay)
# set rỗng
22.5 Vòng lặp với Set
Dù không có số thứ tự, bạn vẫn có thể dùng vòng lặp for để duyệt qua từng phần tử trong Set.
Ví dụ:
trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}
for x in trai_cay:
print(f"Trai cay: {x}")
22.6 Gộp các Set
Bạn có thể sử dụng phương thức union() hoặc update() để gộp 2 Set.
Phương thức union()
Phương thức union() trả về một Set mới, chứa tất cả các phần tử không trùng lặp từ cả hai Set. Hai Set ban đầu vẫn giữ nguyên giá trị.
Ví dụ,
trai_cay1 = {"Cam", "Xoai"}
trai_cay2 = {"Mit", "Xoai", "Bo"}
trai_cay = trai_cay1.union(trai_cay2)
print(trai_cay)
# Cam, Xoai, Mit, Bo
print(trai_cay1)
print(trai_cay2)
Phương thức update()
Phương thức update() sẽ thêm trực tiếp toàn bộ phần tử của Set này vào Set khác. Set gốc sẽ bị thay đổi dữ liệu.
Ví dụ:
trai_cay1 = {"Cam", "Xoai"}
trai_cay2 = {"Mit", "Xoai", "Bo"}
trai_cay1.update(trai_cay2)
print(trai_cay1)
# Cam, Xoai, Mit, Bo
22.7 Frozenset
Frozenset là một kiểu Set đặc biệt. Khi đã tạo một frozenset, bạn không thể thêm, xóa hay sửa đổi các phần tử bên trong nó.
frozenset thường được dùng để định nghĩa một tập hợp các giá trị cố định, giúp bảo vệ dữ liệu tránh vô tình bị thay đổi trong quá trình chạy chương trình.
Ví dụ:
trai_cay1 = frozenset({"Cam", "Xoai"})
trai_cay1.add("Bom")
# Lenh add() se bao loi
22.8 Bài tập và câu hỏi
Bài tập
Bài tập 22a: Bạn đang chuẩn bị một bữa tiệc sinh nhật. Hãy viết đoạn mã quản lý khách mời. Gồm các công việc sau:
- Tạo một Set, đặt tên là khach_moi để chứa tên các khách mời: "Teo", "Ti", "Suu"
- Thêm "Mao" vào khach_moi
- Vì "Ti" bận không đi được, hãy xóa "Ti" khỏi Set
- In ra thông báo: "Có tổng cộng [số lượng] bạn sẽ đến dự tiệc." Gợi ý: Dùng hàm len() để tính số lượng bạn đến dự tiệc.
Bài tập 22b: Kiểm tra thẻ thư viện.
Thư viện trường có một Set các ID thẻ đã đăng ký: {101, 102, 105, 108}.
Viết chương trình cho phép bạn nhập một số ID từ bàn phím, sau đó kiểm tra xem ID đó đã có trong hệ thống chưa và in ra thông báo tương ứng.
Bài tập 22c: Lọc phần tử trùng lặp.
Bạn có một danh sách (list) chứa nhiều màu sắc, trong đó có một số màu bị lặp lại: colors = ["do", "xanh", "do", "vang", "xanh"].
Hãy viết mã để biến danh sách này thành một Set để loại bỏ các màu trùng, sau đó in kết quả ra màn hình.
Câu hỏi ôn tập
22.1 Đặc điểm nào sau đây không phải của Set?
A. Không có thứ tự
B. Có thể chứa các phần tử trùng lặp
C. Được bao bởi dấu { }
D. Có thể thêm phần tử sau khi tạo
22.2 Để thêm một phần tử vào Set, sử dụng phương thức nào?
A. append()
B. insert()
C. add()
D. update()
22.3 Sự khác biệt giữa set và frozenset là gì?
A. Set dùng ngoặc nhọn, Frozenset dùng ngoặc vuông
B. Set không cho phép trùng lặp, Frozenset cho phép
C. Set có thể thay đổi dữ liệu, Frozenset thì không
D. Set chỉ chứa số, Frozenset chỉ chứa chữ
22. Set Data Type
In previous lessons, we covered the List, Tuple, and Dictionary data types. In this lesson, we will explore another fundamental data type in Python: the Set.
22.1 What is a Set?
Imagine you have a bag of colored marbles with the following properties:
- Unordered: You do not care which marble was added first or last
- Unique elements: If you put two identical blue marbles into the bag, it automatically treats them as a single blue marble (duplicate values are not stored)
These are the two key characteristics of a Set.
In Python, a Set is defined using curly braces {} with elements separated by commas.
Example:
# Declare a Set of school subjects
subjects = {"Math", "Literature", "English", "Math"}
print(subjects)
# Output: {'Math', 'English', 'Literature'} (Note: The duplicate 'Math' element was automatically removed)
22.2 Accessing Set Elements
Because Sets are unordered, their elements do not have index numbers like Lists. You cannot use subjects[0] to retrieve the first element.
To check whether an element exists within a Set, use the in keyword.
Example:
subjects = {"Math", "Literature", "English"}
print("Math" in subjects)
# Output: True
22.3 Adding Elements to a Set
To add elements to a Set, you can use two built-in methods:
- add(): Adds a single element
- update(): Adds multiple elements from an iterable (such as a List or another Set)
Example:
fruits = {"Apple", "Orange"}
fruits.add("Mango") # Add a single element
fruits.update(["Plum", "Peach"]) # Add multiple elements
print(fruits)
22.4 Removing Elements from a Set
You can remove elements from a Set using three different methods:
[1] remove(): Removes a specified element. If the element does not exist, it raises a KeyError.
Example:
fruits = {"Apple", "Orange", "Mango", "Banana"}
# 1. Remove an existing element
fruits.remove("Orange")
print("Set after removing 'Orange':", fruits)
# Output: {'Apple', 'Mango', 'Banana'}
# 2. Removing a NON-EXISTENT element (raises a KeyError)
try:
fruits.remove("Watermelon")
except KeyError as e:
print(f"Error: Element {e} not found for removal!")
- [2] discard(): Removes a specified element. If the element does not exist, it does nothing and does not raise an error
- [3] clear(): Removes all elements, leaving an empty Set
Example:
fruits = {"Apple", "Orange", "Mango", "Banana"}
fruits.clear()
print(fruits)
# Output: set() (an empty set)
22.5 Iterating Through a Set
Although Sets lack indexed positions, you can still use a for loop to iterate through each element in a Set.
Example:
fruits = {"Apple", "Orange", "Mango", "Banana"}
for item in fruits:
print(f"Fruit: {item}")
22.6 Joining Sets
You can merge two Sets using either the union() or update() method.
The union() Method
The union() method returns a new Set containing all unique elements from both original Sets. The original Sets remain unchanged.
Example:
fruits1 = {"Orange", "Mango"}
fruits2 = {"Jackfruit", "Mango", "Avocado"}
all_fruits = fruits1.union(fruits2)
print(all_fruits) # Output: Orange, Mango, Jackfruit, Avocado
print(fruits1) # Unchanged
print(fruits2) # Unchanged
The update() Method
The update() method modifies the original Set in place by inserting all elements from another Set into it.
Example:
fruits1 = {"Orange", "Mango"}
fruits2 = {"Jackfruit", "Mango", "Avocado"}
fruits1.update(fruits2)
print(fruits1)
# Output: Orange, Mango, Jackfruit, Avocado
22.7 Frozenset
A frozenset is an immutable variant of a Set. Once created, its elements cannot be added, removed, or modified.
frozenset is typically used to define fixed collections of values, preventing accidental data modification during execution. Furthermore, because it is immutable and hashable, a frozenset can be used as a Dictionary key or as an element within another Set.
Example:
fruits1 = frozenset({"Orange", "Mango"})
fruits1.add("Apple")
# AttributeError: 'frozenset' object has no attribute 'add'
22.8 Exercises and Review Questions
Exercises
Exercise 22a: You are organizing a birthday party. Write a program to manage your guest list following these steps:
- Create a Set named guest_list containing the names: "Teo", "Ti", "Suu"
- Add "Mao" to guest_list
- Since "Ti" cannot make it, remove "Ti" from the Set
- Print a message: "A total of [number] friends will attend the party." (Hint: Use the len() function to calculate the count)
Exercise 22b: Library Card Validation. A university library maintains a Set of registered card IDs: {101, 102, 105, 108}.
Write a program that prompts the user to enter an ID from the keyboard, checks whether that ID exists in the system, and displays an appropriate message.
Exercise 22c: Filtering Duplicate Elements. You have a List containing various colors, including duplicate entries: colors = ["red", "blue", "red", "yellow", "blue"].
Write code to convert this List into a Set to eliminate duplicate colors, then print the result to the screen.
Review Questions
22.1 Which of the following is NOT a characteristic of a Set?
A. Unordered
B. Can contain duplicate elements
C. Enclosed in curly braces {}
D. Mutable (elements can be added after creation)
22.2 Which method is used to add a single element to a Set?
A. append()
B. insert()
C. add()
D. update()
22.3 What is the difference between a set and a frozenset?
A. set uses curly braces; frozenset uses square brackets.
B. set does not allow duplicates; frozenset allows duplicates.
C. set is mutable; frozenset is immutable.
D. set only contains numbers; frozenset only contains text.