Python Lists, Tuples, Dictionaries and Sets Explained with Examples
P4.4 Python Sets: Remove Duplicates and Compare Groups
Why. You often need unique values: how many different cities? Which customers bought in both months? Sets answer this fast.
What. A set is written with {} (without key: value). It keeps only unique values and has no order.
set(list)— remove duplicatesa & b— in botha | b— in eithera - b— in a but not in b
How.
Find unique values
- Put the list into
set(). - Use
len()to count unique items. - Use
&,|,-to compare two sets.
Worked example A — Unique cities.
Step 1 — What we do. A courier company in Spain has a list of delivery cities with repeats.
Step 2 — Type and run this code.
cities = ["Madrid", "Seville", "Madrid", "Valencia", "Seville"]
unique = set(cities)
print(len(unique))
print(sorted(unique))
Step 3 — Output you should see.
3
['Madrid', 'Seville', 'Valencia']
Step 4 — What it means. There are 3 unique cities. sorted turns the set into an ordered list for printing.
Worked example B — Customers in both months.
Step 1 — What we do. Customer IDs from January and February at an online shop.
Step 2 — Type and run this code.
jan = {"C1", "C2", "C3", "C4"}
feb = {"C3", "C4", "C5"}
print(sorted(jan & feb))
print(sorted(jan - feb))
print(sorted(jan | feb))
Step 3 — Output you should see.
['C3', 'C4']
['C1', 'C2']
['C1', 'C2', 'C3', 'C4', 'C5']
Step 4 — What it means. & = came back in Feb (C3, C4). jan - feb = did not return (C1, C2). | = all customers. This is a quick retention check.
Ravindra Bagale's Tip
Use sets for "unique" and "who is missing" questions. They are much faster than checking a list item by item.
Ravindra Bagale's Tip – मराठी
"Unique" आणि "कोण गायब आहे" या प्रश्नांसाठी sets वापरा. List मध्ये एकेक item तपासण्यापेक्षा हे खूप जलद आहे.
Ravindra Bagale's Tip – हिंदी
"Unique" और "कौन गायब है" वाले सवालों के लिए sets इस्तेमाल करो. List में एक-एक item check करने से ये बहुत तेज़ है.