Saturday, July 2, 2022

Python - Set joins

# We can combine two sets with the union method
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)

# {'a', 1, 2, 3, 'c', 'b'}
print(set3)

# Add items from set2 to set1
set1.update(set2)
print (set1)

# Both union and update exclude duplicates

# intersection_update keeps only items that are present in both sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)
# {'apple'}
print(x)

# intersection() returns a NEW set of items present in both sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)
# {'apple'}
print(z)

# Keep all but NOT the duplicates
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)
# {'cherry', 'microsoft', 'google', 'banana'}
# Notice no 'apple'
print(x)