Sets are another important data structure in Python. They differ from dictionaries in that they do not have keys and they differ from tuples in that they are both mutable and unordered.
Examples
A simple set:
employee_name = {"Peter", "Johnson"}
Intersecting between two sets:
set1 = {"Peter", "Johnson"}
set2 = {"James"}
result = set1 | set2 # {'Johnson', 'James', 'Peter',}
We can also get the difference between two sets:
set1 = {"Peter", "Johnson"}
set2 = {"James"}
result = set1 - set2 # {'Peter', 'Johnson'}
A set can be checked if it is a superset of another set:
set1 = {"Peter", "Johnson"}
set2 = {"James"}
superset = set1 > set2 # False
We can get the length of a set using the len()
method:
employee_name = {"Peter", "Johnson"}
len(set1) # 2
We can create a list by passing the set:
employee_name = {"Peter", "Johnson"}
list(employee_name)
We can check if an element is contained in a set using in
:
print("Peter" in employee_name) # True