Python Tutorial › Data Structures › Sets

Python Sets

BeginnerLesson 22 of 4710 min read9 runnable examples

A set is an unordered collection of unique items. Sets remove duplicates automatically, answer “is this item here?” very fast, and support the union and intersection operations you know from maths.

Advertisement
In this lesson
  • Create sets and remove duplicates
  • Add and remove items safely
  • Union, intersection and difference
  • Subset checks and frozenset

Create a set

Write items inside curly braces, or call set() on any iterable. Duplicates are dropped.

Python
tags = {"python", "testing", "python", "api"}print(len(tags))print(sorted(tags)) letters = set("mississippi")print(sorted(letters))
Output
3
['api', 'python', 'testing']
['i', 'm', 'p', 's']
Watch out

{} creates an empty dictionary, not a set. Use set() for an empty set.

Python
print(type({}).__name__, type(set()).__name__)
Output
dict set

Sets are unordered

A set has no positions, so there is no indexing or slicing. Loop over it, or convert it to a sorted list when you need an order.

Python
colors = {"red", "green", "blue"}print(sorted(colors))print(colors[0])
Output
['blue', 'green', 'red']
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(colors[0])
          ~~~~~~^^^
TypeError: 'set' object is not subscriptable

Membership is fast

Checking x in some_set takes about the same time however big the set is, while x in some_list has to look through the items one by one. For repeated lookups, convert to a set first.

Python
blocked = {"spam.com", "bad.org", "phish.net"}for domain in ["good.in", "bad.org"]:    print(domain, "blocked" if domain in blocked else "allowed")
Output
good.in allowed
bad.org blocked

Add and remove items

Python
skills = {"python", "sql"}skills.add("selenium")skills.update(["playwright", "python"])   # add severalprint(sorted(skills)) skills.remove("sql")       # KeyError if missingskills.discard("java")     # no error if missingprint(sorted(skills)) item = skills.pop()        # removes an arbitrary itemprint(len(skills))
Output
['playwright', 'python', 'selenium', 'sql']
['playwright', 'python', 'selenium']
2

Set operations

OperationOperatorMethodResult
Uniona | ba.union(b)Items in either set
Intersectiona & ba.intersection(b)Items in both
Differencea - ba.difference(b)Items in a but not b
Symmetric differencea ^ ba.symmetric_difference(b)Items in exactly one
Python
python_devs = {"asha", "ravi", "meena", "john"}java_devs = {"ravi", "john", "sara"} print(sorted(python_devs | java_devs))print(sorted(python_devs & java_devs))print(sorted(python_devs - java_devs))print(sorted(python_devs ^ java_devs))
Output
['asha', 'john', 'meena', 'ravi', 'sara']
['john', 'ravi']
['asha', 'meena']
['asha', 'meena', 'sara']

Subsets and supersets

Python
required = {"python", "sql"}candidate = {"python", "sql", "git"} print(required <= candidate)          # issubsetprint(candidate >= required)          # issupersetprint(required.isdisjoint({"java"}))  # no items in common
Output
True
True
True

Remove duplicates from a list

Python
emails = ["a@x.com", "b@x.com", "a@x.com"]print(len(set(emails)))                   # count of unique itemsprint(sorted(set(emails)))print(list(dict.fromkeys(emails)))        # unique AND original order
Output
2
['a@x.com', 'b@x.com']
['a@x.com', 'b@x.com']

frozenset

A frozenset is an immutable set. Because it cannot change, it can be a dictionary key or an item of another set.

Python
team_a = frozenset({"asha", "ravi"})history = {team_a: "won final"}print(history[frozenset({"ravi", "asha"})])
Output
won final

Check your understanding

Predict the output

a = {1, 2, 3, 4}b = {3, 4, 5}print(sorted(a - b), sorted(b - a), len(a | b), a & b == {3, 4})

Quick quiz

1. What does {} create?

2. Which method does NOT raise an error when the item is missing?

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

Exercise: common and unique skills

Two candidates list their skills. Print the skills they share, the skills only the first has, and how many different skills they have together.

Input
c1 = ["python", "sql", "git", "docker"], c2 = ["java", "sql", "git"]
Expected output
Shared: ['git', 'sql']
Only first: ['docker', 'python']
Total different: 5
Hint 1

Convert both lists to sets first.

Program Practice

Python sets FAQ

Is a Python set ordered?

No. Sets do not keep insertion order and cannot be indexed. Use sorted(s) to get an ordered list.

How do I create an empty set in Python?

Use set(). {} creates an empty dictionary.

What is the difference between remove() and discard()?

Both remove an item. remove() raises KeyError if the item is missing; discard() does nothing.

Can a set contain a list?

No. Set items must be hashable. Use a tuple instead of a list.

1 thought on “Python Sets”

Leave a Comment