xxxxxxxxxx
1
2
3
4
combined = fruits.union(colors)
common = fruits.intersection(colors)
unique_to_fruits = fruits.difference(colors)
sym_diff = fruits.symmetric_difference(colors)
Copied!
xxxxxxxxxx
>>> A = {0, 2, 4, 6, 8};
>>> B = {1, 2, 3, 4, 5};
>>> print("Union :", A | B)
Union : {0, 1, 2, 3, 4, 5, 6, 8}
>>> print("Intersection :", A & B)
Intersection : {2, 4}
>>> print("Difference :", A - B)
Difference : {0, 8, 6}
# elements not present both sets
>>> print("Symmetric difference :", A ^ B)
Symmetric difference : {0, 1, 3, 5, 6, 8}
xxxxxxxxxx
myNewSet = set()
myNewSet.add("what have you done")
myNewSet.add("to earn your place")
myNewSet.add("in this crowded world?")
"what have you done" in myNewSet # -> true
myNewSet.remove("to earn your place")
# -> myNewSet = {"what have you done", "in this crowded world?"}
xxxxxxxxxx
# Creating an empty set
b = set()
print(type(b))
## Adding values to an empty set
b.add(4)
b.add(4)
b.add(5)
b.add(5) # Adding a value repeatedly does not changes a set
b.add((4, 5, 6))
## Accessing Elements
# b.add({4:5}) # Cannot add list or dictionary to sets
print(b)
## Length of the Set
print(len(b)) # Prints the length of this set
## Removal of an Item
b.remove(5) # Removes 5 fromt set b
# b.remove(15) # throws an error while trying to remove 15 (which is not present in the set)
print(b)
print(b.pop())
print(b)
xxxxxxxxxx
A_Set = {1, 2, "hi", "test"}
for i in A_Set: #Loops through the set. You only get the value not the index
print(i) #Prints the current value
xxxxxxxxxx
1
2
3
4
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
sym_diff_set = set1.symmetric_difference(set2)
Copied!
xxxxxxxxxx
#Definition: A collection of values (similiar spirit to python dictionary)
# implementing hash table as a data structure underneath the hood.