← Python lessons

Python Set Operations: Intersection, Union and Difference

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Set operations make a new set from two sets: & (intersection) keeps the values in both, | (union) those in either, - (difference) the first's only.

Before this lesson you should know how to make a set and add to it: see Sets and Tuples.

Values in both sets: intersection

Here each set is written with its values inside curly brackets. a & b is a new set of the values that are in a and also in b:

chess = {"Mia", "Tom", "Zoe"}art = {"Tom", "Zoe", "Ali"}print(sorted(chess & art))

It printed ['Tom', 'Zoe']: they are in both clubs. A set has no order, so sorted() prints it the same way every time. An empty set is written set(), because {} is an empty dictionary.

Values in either set: union

a | b is a new set of every value in a or b, each one once:

chess = {"Mia", "Tom", "Zoe"}art = {"Tom", "Zoe", "Ali"}print(sorted(chess | art))print(len(chess | art))

It printed the four names, then 4. "Tom" and "Zoe" are in both sets, but the union holds them once.

Values in the first set only: difference

a - b is a new set of the values in a that are not in b. The order matters:

chess = {"Mia", "Tom", "Zoe"}art = {"Tom", "Zoe", "Ali"}print(sorted(chess - art))print(sorted(art - chess))

It printed ['Mia'], then ['Ali']. None of these operators changes chess or art.

Combine set operators with brackets

Brackets work as in maths: the part inside them happens first. Here the union of both clubs is taken away from the whole class:

pupils = {"Mia", "Tom", "Zoe", "Ali", "Sam", "Lee"}chess = {"Mia", "Tom", "Zoe"}art = {"Tom", "Zoe", "Ali"}print(sorted(pupils - (chess | art)))

It printed ['Lee', 'Sam']: the pupils in neither club.

Note: without the brackets, pupils - chess | art takes away chess first and then adds every name in art back.

See also: Sets and Tuples, Sorting.

Your turn

Add two prints: the foods that only Mia likes, in sorted order, then how many different foods the two of them like.

🎯 Goal — make it print exactly:
['soup']
4
mia = {"soup", "pizza", "rice"}tom = {"pizza", "rice", "pie"}# print the sorted foods only Mia likes, then how many foods either likes (two lines)