Lesson 14 · 14 of 20
Sets · Python
Remove duplicates with Python sets and compare groups with intersection, union and difference: who belongs to each school club.

A set keeps each value only once. set(visits) turns the list of six visits into a set of three people: the duplicates simply vanish.
Sets have no order, and when printed their items can come out in any order. That is why the example uses sorted(), which returns a sorted list of the items, so the output is always the same.
A set can also be written between braces, like chess and football. With them you can do set operations: & (intersection) gives who is in both clubs; | (union) who is in either; - (difference) who is only in chess; and ^ who is in just one of the two.
add() adds an item; if it is already there, like ben, nothing happens. discard() removes it without an error even when it is missing. And in checks membership, much faster than in a long list.
Code · main.py
# A set keeps each value only once. It uses { } or set().visits = ["ana", "ben", "ana", "carla", "ben", "ana"]people = set(visits)print("Visits:", len(visits), "| Different people:", len(people))# A set has no order: sorted() gives a sorted list to print.print("Who came:", sorted(people))# Two clubs at school: who is in each one?chess = {"ana", "ben", "carla", "dani"}football = {"ben", "dani", "eva", "fran"}print("Both clubs:", sorted(chess & football))print("Any club:", sorted(chess | football))print("Only chess:", sorted(chess - football))print("Just one club:", sorted(chess ^ football))# add() and discard() change the set.football.add("ana")football.add("ben") # already there: nothing changesfootball.discard("fran")print("Football now:", sorted(football))print("Is eva in chess?", "eva" in chess)Output · python3 main.py
Visits: 6 | Different people: 3 Who came: ['ana', 'ben', 'carla'] Both clubs: ['ben', 'dani'] Any club: ['ana', 'ben', 'carla', 'dani', 'eva', 'fran'] Only chess: ['ana', 'carla'] Just one club: ['ana', 'carla', 'eva', 'fran'] Football now: ['ana', 'ben', 'dani', 'eva'] Is eva in chess? False
Key points
- A
sethas no duplicates and no order. set(items)removes the duplicates from a list.&common,|all,-difference,^in only one.sorted()gives a sorted list for printing a set.
Exercise
Create a third club, music, and print who is in all three clubs and who is in chess or music but not in football.