Lesson 47 +10 XP

Join Sets

Join Sets

Python has several ways to combine sets, and the choice matters.

union() or |

Combines all items from both sets, new set, no duplicates:

set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)  # {'a', 'b', 'c', 1, 2, 3}

The | operator does the same thing.

update() or |=

Adds items of one set into another (in place):

set1.update(set2)

intersection() or &

Keeps only items in BOTH sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)  # {'apple'}

intersection_update() does it in place.

difference() or -

Keeps items only in the FIRST set:

z = x.difference(y)
print(z)  # {'banana', 'cherry'}

symmetric_difference() or ^

Keeps items in EITHER set, but not both:

z = x.symmetric_difference(y)
print(z)  # {'banana', 'cherry', 'google', 'microsoft'}

TL;DR

  • union() (|) joins everything.
  • intersection() (&) keeps items in both.
  • difference() (-) keeps items only in the first.
  • symmetric_difference() (^) keeps items in either but not both.