Ravindra BagaleCourses & study guides मराठी Track your progress

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 duplicates
  • a & b — in both
  • a | b — in either
  • a - b — in a but not in b

How.

Find unique values

  1. Put the list into set().
  2. Use len() to count unique items.
  3. 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.