← Back to Python, page 2

python-0032 · Easy fresher

How do set operations work, and when are sets the right tool?

Sets store unique hashable items with fast membership tests. Union (|), intersection (&), difference (-) and symmetric difference (^) compare collections directly. Use sets to deduplicate, to find common or missing items, and for fast 'in' checks; they do not keep order.

Full answer
python
python_students = {"Asha", "Ben", "Chen"}
sql_students = {"Ben", "Dara", "Chen"}
print(sorted(python_students | sql_students))
print(sorted(python_students & sql_students))
print(sorted(python_students - sql_students))
print(sorted(python_students ^ sql_students))
print("Ben" in sql_students, {"Ben"} <= python_students)
tags = ["sql", "python", "sql"]
print(len(set(tags)), list(dict.fromkeys(tags)))

Output:

text
['Asha', 'Ben', 'Chen', 'Dara']
['Ben', 'Chen']
['Asha']
['Asha', 'Dara']
True True
2 ['sql', 'python']

Results are wrapped in sorted() because set order varies between runs, which matters in tests and examples. Intersection shows who takes both courses; difference shows who takes Python only; symmetric difference shows people in exactly one. <= tests for a subset. set(tags) removes duplicates but loses order, while dict.fromkeys keeps the first-seen order. Only hashable items such as strings, numbers and tuples can be set members.

python
python_students = {"Asha", "Ben", "Chen"}
sql_students = {"Ben", "Dara", "Chen"}
print(sorted(python_students | sql_students))
print(sorted(python_students & sql_students))
print(sorted(python_students - sql_students))
print(sorted(python_students ^ sql_students))
print("Ben" in sql_students, {"Ben"} <= python_students)
tags = ["sql", "python", "sql"]
print(len(set(tags)), list(dict.fromkeys(tags)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Sets hold unique hashable items
  • | & - ^ compare collections
  • Membership is fast
  • Order is not preserved
  • dict.fromkeys deduplicates in order

Common mistakes

  • Relying on set iteration order
  • Trying to put lists into sets

Follow-ups

  • What is a frozenset for?
  • How would you find duplicates in a list?

Tips

  • Sort sets before printing