Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Organise the chaos
EXPERIMENT 13 / 101

No duplicates allowed.

Find unique values, overlaps, and the differences between collections.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

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.

sets.py
frontend = {"Python", "JavaScript"}
backend = {"Python", "SQL"}

print(sorted(frontend & backend))
print(sorted(frontend | backend))
print(sorted(frontend - backend))
↳ EXPECTED OUTPUT
['Python']
['JavaScript', 'Python', 'SQL']
['JavaScript']

03 Under the hood

  1. 1

    The & operator finds the shared language. Duplicates appear only once in a set.

  2. 2

    The | operator produces the union. Sorting the result gives a deterministic list for display.

  3. 3

    The - operator is directional. frontend - backend differs from backend - frontend. Use in to test membership without caring about position.

04 Your turn, builder

A SMALL MISSION

Remove duplicates from ["build", "test", "build", "ship"] and print the unique values in sorted order.

Reveal one possible solution +
one_possible_solution.py
steps = ["build", "test", "build", "ship"]
print(sorted(set(steps)))

05 Check your signal

QUICK SIGNAL CHECK

How do you create an empty set?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.