How to understand sets in Python?
In Python, a Set is a mutable, unordered container where elements are unique. A Set can be created using curly braces {} or by using the set() function.
The main characteristics of Set are as follows:
- The elements in the set are unique, meaning each element can only appear once.
- The elements in a Set are unordered and do not have a fixed position or order.
- The elements in Set must be immutable, meaning they can only include immutable data types such as numbers, strings, and tuples, and cannot include mutable data types such as lists or dictionaries.
Common operations with the set include:
- Add elements: Use the add() method to add elements to the Set.
- Remove elements: Use the remove() method to delete elements from the Set.
- To check if an element exists: use the ‘in’ keyword to determine if the element is in the Set.
- Get the size of a Set: Use the len() function to obtain the number of elements in the Set.
- Set operations: including union (|), intersection (&), difference (-), and so on.
Here are some sample codes to better understand the use of Set:
# 创建一个Set
my_set = {1, 2, 3, 4, 5}
print(my_set) # 输出: {1, 2, 3, 4, 5}
# 添加元素
my_set.add(6)
print(my_set) # 输出: {1, 2, 3, 4, 5, 6}
# 删除元素
my_set.remove(3)
print(my_set) # 输出: {1, 2, 4, 5, 6}
# 判断元素是否存在
print(2 in my_set) # 输出: True
print(3 in my_set) # 输出: False
# 获取Set的大小
print(len(my_set)) # 输出: 5
# 集合运算
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 | set2) # 输出: {1, 2, 3, 4, 5, 6, 7, 8},并集
print(set1 & set2) # 输出: {4, 5},交集
print(set1 - set2) # 输出: {1, 2, 3},差集
In general, a Set is a very useful data structure that can be used for operations such as removing duplicates and set operations.