📜  Python set()(1)

📅  最后修改于: 2023-12-03 14:46:04.002000             🧑  作者: Mango

Python Set()

Introduction

In Python, a set is an unordered collection of unique elements. It is part of the built-in set data type. Sets are commonly used to eliminate duplicate elements from a list or to perform mathematical set operations such as union, intersection, and difference.

Creating a Set

A set can be created using the set() function or by enclosing elements in curly braces ({}):

my_set = set()  # empty set
my_set = {1, 2, 3}  # set with elements
Adding and Removing Elements

Elements can be added to a set using the add() method or multiple elements can be added using the update() method:

my_set.add(4)
my_set.update([5, 6, 7, 8])

To remove elements from a set, the remove() method can be used:

my_set.remove(2)
Basic Set Operations
Union

The union of two sets can be obtained using the union() method or the | operator:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# Alternatively: union_set = set1 | set2
Intersection

The intersection of two sets can be obtained using the intersection() method or the & operator:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# Alternatively: intersection_set = set1 & set2
Difference

The difference between two sets can be obtained using the difference() method or the - operator:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
# Alternatively: difference_set = set1 - set2
Subset and Superset

To check if a set is a subset or superset of another set, use the issubset() and issuperset() methods:

set1 = {1, 2}
set2 = {1, 2, 3, 4, 5}
set3 = {6, 7}
print(set1.issubset(set2))  # Output: True
print(set1.issuperset(set3))  # Output: False
Set Operations Without Modifying Sets

When performing set operations, it is important to note that the original sets remain unmodified. New sets are returned with the desired results.

Conclusion

Python set() is a powerful data type for storing unique elements. It provides methods to perform set operations like union, intersection, and difference. Sets are mutable, unordered, and iterable. They are useful in various scenarios where distinct values are required or mathematical set operations need to be performed.