Set Operations
Set Operations
In [ ]: 1 #set operations
2
3 union:
4 #union() method allows you to join a set with other data types,
5 #like lists or tuples.
6
7 #union() and update() will exclude any duplicate items.
In [7]: 1 #union method returns a new set with all items from both sets.
2 set1 = {"a", "b", "c"}
3 set2 = {1, 2, 3}
4 set3 = set1.union(set2)
5 print(set3)
6
In [6]: 1 #union() method allows you to join a set with other data types
2
3 x = {"a", "b", "c"}
4 y = (1, 2, 3)
5 z = x.union(y)
6 print(z)
In [7]: 1 #The | operator only allows you to join sets with sets,
2 # other data types like you can with the union() method.
3 x = {"a", "b", "c"}
4 y = (1, 2, 3)
5 z=x|y
6 print(z)
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[7], line 4
2 x = {"a", "b", "c"}
3 y = (1, 2, 3)
----> 4 z=x|y
5 print(z)
In [ ]: 1 #Intersection
2
3 #The intersection() method will return a new set, that only contains th
4 #Keep ONLY the duplicates
{'apple'}
{'apple'}
{False, 1, 'apple'}
In [ ]: 1 #Difference
2
3 #difference() method will return a new set
4 #that will contain only the items from the first set
5 #that are not present in the other set.
6
7
In [16]: 1 #Keep all items from set1 that are not in set2:
2 set1 = {"apple", "banana", "cherry"}
3 set2 = {"google", "microsoft", "apple"}
4 set3 = set1.difference(set2)
5 print(set3)
{'cherry', 'banana'}
{'cherry', 'banana'}
In [14]: 1 #The difference_update() method will also keep the items from the first
2 #that are not in the other set,
3 #but it will change the original set instead of returning a new set
4 set1 = {"apple", "banana", "cherry"}
5 print("original set",set1)
6 set2 = {"google", "microsoft", "apple"}
7 set1.difference_update(set2)
8 print("difference_update",set1)
9
In [ ]: 1 #Symmetric Differences
2
3 # will keep only the elements that are NOT present in both sets.
4
In [ ]: 1 #symmetric_difference_update()
2 #keep all but the duplicates,
3 #but it will change the original set instead of returning a new set.
In [ ]: 1 #issubset()
2 #returns True if all items in the set exists in the specified set,
3 #otherwise it returns False.
True
True
In [ ]: 1 #issuperset()
2 #returns True if all items in the specified set exists in the original
3 #otherwise it returns False.
True
True
In [ ]: 1 #isdisjoint()
2 #returns True if none of the items are present in both sets,
3 #otherwise it returns False.
True
In [ ]: 1