Sets: Unique Collections and Membership
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A set is an unordered collection of unique, hashable elements. Sets are used to remove duplicates and perform instantaneous O(1) membership checks.
Creating sets and removing duplicates
Set is a collection of unique values with no order and no positions. Adding a value that is already in the set changes nothing, so a set is a quick way to remove duplicates.
Create a set using {element1, element2} or convert a list using set(). Notice that duplicates are discarded automatically.
nums = [1, 2, 2, 3, 4, 4, 4]unique_nums = set(nums)print(unique_nums)Example 1 · Counting different customers
customer_ids = [101, 102, 101, 103, 102, 101]unique_ids = set(customer_ids)print(f"Orders received: {len(customer_ids)}")print(f"Different customers: {len(unique_ids)}")print(sorted(unique_ids))Orders received: 6 Different customers: 3 [101, 102, 103]
What this code does
set(customer_ids)keeps one copy of each id.- The list still has 6 orders, but the set has only 3 customers.
sortedgives a list in a fixed order for printing.
The duplicates are eliminated, producing {1, 2, 3, 4}.
Empty set syntax: set() NOT {}
set() is a built-in call that makes a set from any sequence, such as a list or a string. Called with nothing inside, it makes an empty set. Plain {} makes an empty dictionary instead.
To create an empty set, you MUST write set(). Writing {} creates an empty dictionary.
empty_s = set()empty_d = {}print(type(empty_s))print(type(empty_d))The console confirms empty_s is <class 'set'> while empty_d is <class 'dict'>.
Adding and removing elements
Use .add(x) to insert an element. To remove, .discard(x) is safer than .remove(x) because it never raises an error if the item is missing.
tags = {"python", "fastapi"}tags.add("docker")tags.discard("kubernetes")print(sorted(tags))Example 2 · Managing a skills list
skills = {"python", "sql"}skills.add("docker")skills.add("python")skills.discard("java")print(sorted(skills))print(len(skills))['docker', 'python', 'sql'] 3
What this code does
add("docker")puts in a new skill.- Adding
"python"again changes nothing and raises no error. discard("java")is safe even though the skill was never there.
.discard("kubernetes") does nothing silently since the element was absent.
Membership and order
Membership test is the check x in s, which answers True or False depending on whether the value is in the collection. On a set it is very fast, because Python jumps straight to the value.
Use in to ask whether a value is in a set. A set keeps no order, so you cannot use s[0]. To show the items in a steady order, sort them first.
cities = {"Pune", "Delhi", "Mumbai"}print("Pune" in cities)print("Goa" in cities)print(sorted(cities))Example 3 · Blocking known bad addresses
banned_ips = {"192.168.1.100", "10.0.0.5"}incoming_ip = "192.168.1.100"
# O(1) membership checkif incoming_ip in banned_ips: print(f"Connection rejected from {incoming_ip}")else: print("Connection allowed")Connection rejected from 192.168.1.100
What this code does
- Checks IP presence in the banned set.
- Membership lookup
inruns in instantaneous O(1) constant time.
The two tests print True and False. sorted turns the set into an ordered list, so the output is the same on every run.
Next step
Check your understanding
9 quick questions