Lesson 3 of 5 · Collections · 2 min read · Updated
Sets
Collections with no duplicates and no order — and fast answers to "is this in here?".
A set holds each value at most once, with no order. Turning a list into a set is the quickest way to remove duplicates.
python
visitors = ["ravi", "meena", "ravi", "arun", "meena"]
unique = set(visitors)
print(len(unique))
print("arun" in unique)
print(sorted(unique))
Output
3
True
['arun', 'meena', 'ravi']
Note
A set has no positions, so unique[0] is an error, and the order it prints in can change between runs. Use sorted() when you need a dependable order.
Set operations
python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
Output
{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{1, 2, 5}
a | b— union: in either.a & b— intersection: in both.a - b— difference: in a but not b.a ^ b— symmetric difference: in one but not both.
python
tags = set()
tags.add("python")
tags.add("python")
tags.add("basics")
tags.discard("missing")
print(len(tags))
Output
2
Warning
{} is an empty dictionary, not an empty set. Write set() for an empty set. Adding the same value twice is harmless — it is simply already there.
What is len({1, 1, 2, 2, 3})?
Try this now
- Given two lists of students who joined Python and C classes, print who is in both and who is only in Python.
- Count how many different words there are in a sentence.
Create a free account to save your progress, or sign in.