Understanding Python Sets: Definition, Operations, and Practical Examples
This article introduces Python's set data structure, explains its unordered, unique, and mutable characteristics, demonstrates how to create sets, and provides eleven practical code examples covering basic definitions, element addition and removal, set operations like union, intersection, difference, subset checks, deduplication, iteration, and conditional filtering.
Introduction
In Python programming, a set is a useful data structure for storing unique, unordered elements and supports mathematical operations such as union, intersection, and difference, making it ideal for deduplication, membership checks, and various set computations.
Part 1: Basics
Sets are unordered, contain only unique items, and are mutable, allowing dynamic addition and removal of elements. A set can be defined directly with curly braces, e.g., my_set = {1, 2, 3} , or created from other iterables using the set() function.
Part 2: Use Cases and Examples
Example 1: Basic set definition and printing
# 定义一个简单的集合
fruits = {"苹果", "香蕉", "橙子"}
print("水果集合:", fruits)Example 2: Adding elements to a set
# 向集合中添加新元素
fruits.add("草莓")
print("更新后的水果集合:", fruits)Example 3: Removing elements from a set
# 从集合中移除指定元素
fruits.remove("香蕉")
print("移除香蕉后的水果集合:", fruits)Example 4: Union of two sets
# 定义两个集合
set1 = {"苹果", "香蕉", "橙子"}
set2 = {"草莓", "蓝莓", "橙子"}
union_set = set1.union(set2)
print("两个集合的并集:", union_set)Example 5: Intersection of two sets
intersection_set = set1.intersection(set2)
print("两个集合的交集:", intersection_set)Example 6: Difference of two sets
difference_set = set1.difference(set2)
print("第一个集合相对于第二个集合的差集:", difference_set)Example 7: Subset check
is_subset = set1.issubset(set2)
print("set1 是否为 set2 的子集:", is_subset)Example 8: Removing duplicates using a set
# 定义一个包含重复元素的列表
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print("去重后的数字集合:", unique_numbers)Example 9: Iterating over a set
for fruit in fruits:
print(fruit)Example 10: Filtering with a set comprehension
# 定义一个包含多个字符串的列表
words = ["apple", "banana", "orange", "strawberry"]
filtered_words = {word for word in words if len(word) >= 6}
print("过滤后的单词集合:", filtered_words)Example 11: Symmetric difference of two sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("两个集合的对称差集:", symmetric_difference_set)Conclusion
The examples demonstrate how sets can be used for a wide range of tasks, from simple deduplication to complex set algebra. When using sets, remember their unordered nature, consider performance for large data, choose appropriate methods, and avoid overusing sets when other data structures might be more suitable.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.