No duplicates allowed.
Find unique values, overlaps, and the differences between collections.
01 The idea
A set stores unique, hashable values. It is ideal for membership questions and comparisons between groups. Union combines members; intersection finds shared members; difference finds values in one set but not another. Set iteration order is not a reliable display order.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
frontend = {"Python", "JavaScript"}
backend = {"Python", "SQL"}
print(sorted(frontend & backend))
print(sorted(frontend | backend))
print(sorted(frontend - backend))['Python'] ['JavaScript', 'Python', 'SQL'] ['JavaScript']
03 Under the hood
- 1
The & operator finds the shared language. Duplicates appear only once in a set.
- 2
The | operator produces the union. Sorting the result gives a deterministic list for display.
- 3
The - operator is directional. frontend - backend differs from backend - frontend. Use in to test membership without caring about position.
04 Your turn, builder
Remove duplicates from ["build", "test", "build", "ship"] and print the unique values in sorted order.
Reveal one possible solution +
steps = ["build", "test", "build", "ship"]
print(sorted(set(steps)))05 Check your signal
How do you create an empty set?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.