Rams Poster
What’s a set?
A set is a built‑in collection that holds unique items – duplicates are automatically removed. Think of it as a bag where every element can appear only once.
Why use a set?
- Fast membership test – asking “is this value in the collection?” is lightning quick (average O(1) time) because Python stores items in a hash table.
- Automatic deduplication – you never need to write extra loops to get rid of repeats.
How does it work?
When you add a value, Python computes a hash (a numeric fingerprint) for that value. If the fingerprint already exists, the new value is ignored. This is why only hashable objects (numbers, strings, tuples) can be members of a set.
Creating a set
# start with a list that has repeats
numbers = [1, 2, 3, 2, 4, 1, 5]
# turn it into a set – duplicates disappear
unique_numbers = set(numbers)
print(unique_numbers) # {1, 2, 3, 4, 5}
Common set operations
- Add one item – my_set.add(item)
- Remove an item – my_set.discard(item) (no error if missing)
- Check membership – item in my_set (very fast)
- Set math – union (|), intersection (&), difference (-)
Quick cheat‑sheet (bolded list)
- list – ordered, allows duplicates, slower membership (O(n))
- set – unordered, no duplicates, fast membership (O(1))
Real‑world example: filtering user input
Suppose you ask a user to type several favorite colors, separated by commas, and you want to keep only the distinct ones:
raw = input("Enter colors, separated by commas: ")
# split into a list, strip spaces, lower‑case for uniformity
color_list = [c.strip().lower() for c in raw.split(",")]
# use a set to drop repeats
unique_colors = set(color_list)
print("You gave", len(unique_colors), "different colors:")
print(unique_colors)
Tip: If you later need the unique items in the original order, convert back with a simple loop:
ordered_unique = []
seen = set()
for c in color_list:
if c not in seen:
ordered_unique.append(c)
seen.add(c)
print(ordered_unique) # preserves the order user typed
Remember:
- Use a set whenever you need “no duplicates” or “quick look‑ups”.
- You cannot store mutable types like lists or dictionaries inside a set because they aren’t hashable.
Give it a try! Play with set() in the Python REPL and watch duplicates vanish instantly. 🚀
9 ·