Cấu trúc dữ liệu Set trong Python

Đây là bài 26/54 bài của series môn học Ngôn ngữ lập trình Python

1. Đặc điểm của Set trong Python

Set là cấu trúc dữ liệu giúp lưu trữ nhiều các phần tử. Nhưng các phần tử trong Set không có thứ tự (unordered), không thể thay đổi (unchangeable) và không được đánh chỉ mục (unindexed). Đặc biệt là Set không cho phép 2 phần tử giống nhau tồn tại trong nó.

Để tạo ra một Set trong Python, chúng ta đặt các phần tử của Set trong dấu ngoặc nhọn (curly bracket). Ví dụ:

# Set include string
my_set = {'goc', 'it', 'hoc', 'com'}
print("Set include string:", my_set)

# Set include integer
my_set = {1, 0, -1, 9, 5}
print("Set include integer:", my_set)

# Set include string, integer and boolean
my_set = {'gochocit', 7, False, 2, True}
print("Set include string, integer and boolean:", my_set)

# Set include float, tuple
my_set = {7.5, ('goc', 'hoc', 'it')}
print("Set include float, list, tuple:", my_set)
Kết quả
Set include string: {'hoc', 'com', 'it', 'goc'}
Set include integer: {0, 1, 5, 9, -1}
Set include string, integer and boolean: {False, True, 2, 'gochocit', 7}
Set include float, list, tuple: {('goc', 'hoc', 'it'), 7.5}

Các phần tử trong Set có thể có nhiều kiểu dữ liệu khác nhau như string, float, integer, tuple,… Nhưng các phần tử của Set không thể là list, setdictionary.

Và Set không cho phép 2 phần tử giống nhau trong nó. Nếu khai báo 2 phần tử giống nhau trong Set thì nó cũng sẽ chỉ nhận 1 phần tử.

# Set not allowed duplicate items
my_set = {'gochocit', 'com', 'hoc', 'com'}
print("Set not allowed duplicate items:", my_set)
Kết quả
Set not allowed duplicate items: {'hoc', 'com', 'gochocit'}

Sử dụng hàm set() để tạo một Set

# Create set from list
my_set = set(['gochocit', 'hoc', 'com'])
print(my_set)

# Create set from tuple
my_set = set(('hello', 1, -7.5))
print(my_set)

# Create empty set
my_set = set()
print("Create empty set:", type(my_set))

# Cannot create empty set with {}
my_set = {}
print("Cannot create empty set with {}:", type(my_set))
Kết quả
{'gochocit', 'com', 'hoc'}
{1, -7.5, 'hello'}
Create empty set: <class 'set'>
Cannot create empty set with {}: <class 'dict'>

Kích thước của Set trong Python

Sử dụng hàm len() để trả về số lượng phần tử trong Set.

# Sise of set
my_set = set(['gochocit', 'hoc', 'com'])
print("Size of set:", len(my_set))
Kết quả
Size of set: 3

2. Truy cập các phần tử của Set

Các phần tử trong Set không có thứ tự, không được đánh index. Do đó, chúng ta không thể dựa vào index để truy cập các phần tử của Set. Chúng ta chỉ còn cách sử dụng vòng lặp for để duyệt các phần tử trong Set.

my_set = {'gochocit', True, 'hoc', 5, 'com'}
for x in my_set:
  print(x, end=' ')
Kết quả
True gochocit 5 com hoc

Kiểm tra một phần tử có nằm trong Set không?

my_set = {'gochocit', True, 'hoc', 5, 'com'}
# True
print("gochocit" in my_set)
# False
print("hello" in my_set)
Kết quả
True
False

3. Thêm và xóa phần tử trong Set

Các phần tử trong Set không thể thay đổi được nhưng có thể thêm hoặc xóa phần tử trong Set.

3.1. Thêm phần tử vào Set

Sử dụng hàm add()

Hàm add() giúp thêm một phần tử vào Set.

my_set = {'gochocit', True, 5, 'com'}
# Add an item to my_set
my_set.add("hello")
print("Add an item to my_set:", my_set)
# Add an existed item to my_set
# my_set ignored this item
my_set.add("com")
print("Add an existed item to my_set:", my_set)
Kết quả
Add an item to my_set: {True, 'gochocit', 5, 'hello', 'com'}
Add an existed item to my_set: {True, 'gochocit', 5, 'hello', 'com'}

Sử dụng hàm update()

Hàm update() giúp thêm các phần tử của một Set vào một Set khác. Hàm update() cũng có thể giúp thêm các phần tử của một iterable object như list, tuple, dictionary,… vào một Set.

my_set = {'gochocit', True, 5, 'com'}
my_set1 = {2, 3, 9}
# Add set to set
my_set.update(my_set1)
print("Update my_set:", my_set)
# Add list to set
my_list = ["hello", "John"]
my_set.update(my_list)
print("Update my_set:", my_set)
Kết quả
Update my_set: {True, 2, 3, 5, 'com', 'gochocit', 9}
Update my_set: {True, 2, 3, 5, 'com', 9, 'hello', 'gochocit', 'John'}

3.2. Xóa phần tử của Set

Sử dụng hàm remove()

Có chức năng xóa một phần tử trong Set. Nếu phần tử muốn xóa không tồn tại trong Set thì sẽ gây ra lỗi.

my_set = {'gochocit', True, 5, 'com'}
# Remove an item from my_set
my_set.remove("com")
# Output: {True, 'gochocit', 5}
print("Remove an item from my_set", my_set)
# Remove an item which not existed from my_set
# KeyError: 'hello'
my_set.remove("hello")

Sử dụng hàm discard()

Có chức năng xóa một phần tử trong Set. Nếu phần tử muốn xóa không tồn tại trong Set thì sẽ không gây ra lỗi.

my_set = {'gochocit', True, 5, 'com'}
# Discard an item from my_set
my_set.discard("com")
# Output: {'gochocit', 5, True}
print("Remove an item from my_set", my_set)
# Discard an item which not existed from my_set
my_set.discard("hello")

Sử dụng hàm pop()

Chúng ta có thể sử dụng hàm pop() để xóa một item trong Set. Phương thức này sẽ xóa phần tử cuối của Set. Nhưng Set thì không có thứ tự nên chúng ta không biết phần tử nào là phần tử cuối của Set được xóa.

my_set = {'gochocit', True, 5, 'com'}
# Item is removed by pop()
x = my_set.pop()
print("Item is removed by pop():", x)
print("my_set after pop():", my_set)
Kết quả chạy lần 1
Item is removed by pop(): True
my_set after pop(): {'gochocit', 5, 'com'}
Kết quả chạy lần 2
Item is removed by pop(): gochocit
my_set after pop(): {5, 'com', True}
Kết quả chạy lần 3
Item is removed by pop(): com
my_set after pop(): {'gochocit', 5, True}

Sử dụng hàm clear()

Có chức năng xóa tất cả phần tử trong Set. Set sẽ trở thành Set rỗng.

my_set = {'gochocit', True, 5, 'com'}
# Clear my_set
my_set.clear()
print("my_set after clear():", my_set)
Kết quả
my_set after clear(): set()

Sử dụng từ khóa del

Có chức năng xóa hoàn toàn một Set.

my_set = {'gochocit', True, 5, 'com'}
# Delete my_set
del my_set
# NameError: name 'my_set' is not defined
print("my_set after delete:", my_set)

Khi đã xóa biến my_set mà sử dụng lại thì sẽ gây ra lỗi NameError.

5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Các thao tác trên cấu trúc dữ liệu Tuple trong PythonCác thao tác trên cấu trúc dữ liệu Set trong Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.