How to use the set function in Python?
The set() function is used to create a set, which is a collection of unique and unordered elements.
Here is how to use it:
- Create an empty set.
my_set = set()
- Create a collection that contains elements.
my_set = set([1, 2, 3, 4, 5])
- Add elements to the collection.
my_set.add(6)
- Remove elements from the collection.
my_set.remove(1)
- Set operations:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # 求并集
intersection_set = set1.intersection(set2) # 求交集
difference_set = set1.difference(set2) # 求差集