Sets
Unordered list of unique elements
| my_set = {1, 2, 3, 4, 5}
print(my_set)
print(type(my_set))
|
{1, 2, 3, 4, 5}
| print("Unique elements in a list")
numbers = [1, 2, 3, 3, 4, 5, 5, 6]
set(numbers)
|
Unique elements in a list
{1, 2, 3, 4, 5, 6}
| my_set = {1, 2, 3, 4, 5}
my_set.add(6)
print(my_set)
|
{1, 2, 3, 4, 5, 6}
| my_set = {1, 2, 3, 4, 5}
my_set.remove(5) # This will raise an error if 5 is not present
print(my_set)
|
{1, 2, 3, 4}
| my_set = {1, 2, 3, 4, 5}
my_set.discard(6) # This won't raise an error if 6 is not present
print(my_set)
|
{1, 2, 3, 4, 5}
| my_set = {1, 2, 3, 4, 5}
print(my_set.pop()) # This will remove the first inserted element FIFO
print(my_set)
|
1
{2, 3, 4, 5}
| my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set) # This will print an empty set
|
set()
| print("Check if an element is in the set")
my_set = {1, 2, 3, 4, 5}
print(3 in my_set)
|
Check if an element is in the set
True
| print("Union of two sets")
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
print(set1.union(set2))
|
Union of two sets
{1, 2, 3, 4, 5, 6, 7, 8, 9}
| print("Intersection of two sets")
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
intersection_set = set1.intersection(set2)
print(intersection_set)
|
Intersection of two sets
{4, 5, 6}
| print("Update set1 with the intersection of set1 and set2")
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
set1.intersection_update(set2)
print(set1)
|
Update set1 with the intersection of set1 and set2
{4, 5, 6}
| print("Difference of two sets")
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
set1.difference(set2)
|
Difference of two sets
{1, 2, 3}
| print("Symmetric difference of two sets")
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
set1.symmetric_difference(set2)
|
Symmetric difference of two sets
{1, 2, 3, 7, 8, 9}
| print("are all set1 elements present in set2?")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.issubset(set2)
|
are all set1 elements present in set2?
False
| print("are all set2 elements present in set1?")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.issuperset(set2)
|
are all set2 elements present in set1?
False