Skip to content

Beginner · Lists, tuples, dictionaries and sets · topic 17 of 50 · 15 min

Sets: each item only once

Explanation

A set is a collection where each item appears only once, like {"Pune", "Delhi"}. Sets are the easiest way to remove duplicates and to check membership quickly. You can combine two sets with union, intersection and difference. Note that {} makes an empty dict, so an empty set is set().

A set keeps each item only once

A set is a collection of unique items. Unique means each item can appear only once. If you add a duplicate, the set simply ignores it. You write a set with curly braces { }, like a dict, but with single items instead of key: value pairs.

python
cities = {"Pune", "Delhi", "Pune", "Chennai"}
print(len(cities))
print("Delhi" in cities)
The second Pune is dropped, so len is 3. in gives True.
Think of it like this: A set is like the voters' register at a polling booth. When a person votes, their name is marked once. If the same person comes back, they are not counted again. The register tells you who voted, not how many times.

Removing duplicates from a list

python
phones = ["98450", "98111", "98450", "99000", "98111"]
unique = set(phones)
print(len(unique))
print(sorted(unique))
set() turns a list into a set and drops repeats. sorted() gives a neat list back: ['98111', '98450', '99000'].
Careful: Sets are unordered: they do not keep items in the order you added them, and printing a set may show a different order from run to run. So a set has no index, and cities[0] gives TypeError. When order matters, turn the set into a sorted list with sorted(my_set).

Adding and removing

python
present = {"Asha", "Ravi"}
present.add("Meena")
present.add("Asha")
present.discard("Ravi")
present.discard("John")
print(sorted(present))
add puts an item in (adding Asha again changes nothing). discard takes an item out, and does nothing if it is not there. Shows ['Asha', 'Meena'].

There is also remove(), which works like discard but gives KeyError when the item is missing. discard is the safer choice when you are not sure.

Why sets are fast

To check x in my_list, Python looks at the items one by one, which is slow for a lakh of items. A set stores items using a method called hashing, which turns each item into a number that says where it is kept. So x in my_set is almost instant, even for millions of items. If you check membership many times, turn the list into a set first.

Set maths: students in two clubs

python
cricket = {"Asha", "Ravi", "Meena", "Arjun"}
dance = {"Meena", "Priya", "Arjun"}
print(sorted(cricket | dance))
print(sorted(cricket & dance))
print(sorted(cricket - dance))
Union | gives everyone in either club. Intersection & gives students in both: Arjun and Meena. Difference - gives cricket students who do not dance: Asha and Ravi.
OperationSymbolMethodGives
uniona | ba.union(b)items in either set
intersectiona & ba.intersection(b)items in both sets
differencea - ba.difference(b)items in a but not in b
Careful: {} makes an empty dict, not an empty set. To make an empty set, write set().
python
a = {}
b = set()
print(type(a))
print(type(b))
Shows <class 'dict'> and then <class 'set'>.
Tip: A set can only hold values that cannot change, like numbers, strings and tuples. A list cannot go inside a set.

Watch the lesson

Sets: each item only once · 1/7

Sets

In this lesson you will learn sets, collections where each item appears only once.

Prefer a video by a teacher? Find free videos on “python sets tutorial union intersection for beginners” on YouTube ↗

In real life: Finding regular customers

A tea stall owner collects the UPI phone numbers of customers on Monday and on Tuesday. Some people paid twice on the same day. With sets he finds how many different people came, who came on both days (his regulars), and who came only on Tuesday (new faces).

python
monday = ["98450", "98111", "98450", "99000"]
tuesday = ["98111", "97777", "99000", "97777"]
mon = set(monday)
tue = set(tuesday)
print("Different customers Monday:", len(mon))
print("Came both days:", sorted(mon & tue))
print("New on Tuesday:", sorted(tue - mon))
Monday has 3 different customers. Two came both days, and one is new on Tuesday.

Practice (0/3 done)

Task 1 · Code · Python

Write a function unique_count(items) that returns how many DIFFERENT items are in the list. Example: unique_count(["chai", "coffee", "chai", "tea"]) returns 3.

Task 2 · Code · Python

Write a function in_both(club_a, club_b) that takes two lists of names and returns a SORTED list of the names that are in both clubs.

Task 3 · Code · Python

Write a function new_customers(today, regulars) that returns a SORTED list of the people in the list today who are NOT in the list regulars. Each name should appear only once.

Quick quiz

Question 1

1.What does len({1, 2, 2, 3, 3, 3}) give?

Question 2

2.How do you make an empty set?

Question 3

3.What is {1, 2, 3} & {2, 3, 4}?

Question 4

4.s = {"a", "b"}. What does s.discard("z") do?

Question 5

5.Why does s[0] fail for a set?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Dictionaries: look things up by name