Python course · Module 4: Data structures · Lesson 18 of 63
Quick answer: A Python set is an unordered collection with no duplicate items, written in curly brackets: sold = {"Pen", "Notebook", "Pen"} keeps only one "Pen". Create an empty set with set(), because {} makes an empty dictionary. Add items with add(), remove them with remove() or discard(), and check membership with in. Sets also do maths-style operations: a | b (union), a & b (intersection), a - b (difference) and a ^ b (symmetric difference).
In this lesson you will learn:
- how to create a Python set, and why
{}is not an empty set - how to remove duplicates from a list with
set() - how to add and remove items with
add(),update(),remove()anddiscard() - how to compare two sets with union, intersection, difference and symmetric difference
- what can go inside a set, and what a
frozensetis
Before you start: finish Lesson 17, Python Dictionary: Keys, Values, get() and Looping with items(), because sets use the same curly brackets and the same rule for what can go inside. You will also use lists from Lesson 15, Python Lists and List Methods: Indexing, Slicing, Sorting and Copying and for loops from Lesson 12, Python for Loops and range(): Lists, Strings and enumerate(). All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org. Two things differ: the printed order of sets of strings, which changes from run to run anyway, and one longer error message, noted below.
Table of Contents
Create a set
Write the items inside curly brackets, separated by commas. A small shop wrote down each product it sold:
sold = {"Pen", "Notebook", "Pen", "Ruler", "Notebook"}
print(sold)
print(len(sold))
print(type(sold))
We ran this same script three times:
$ python3 step1_create.py
{'Ruler', 'Pen', 'Notebook'}
3
<class 'set'>
$ python3 step1_create.py
{'Notebook', 'Pen', 'Ruler'}
3
<class 'set'>
$ python3 step1_create.py
{'Notebook', 'Pen', 'Ruler'}
3
<class 'set'>
Two things to notice:
- No duplicates. We wrote five items, but the set keeps 3.
- No fixed order. Run 1 printed a different order from runs 2 and 3. Two runs can match by chance, but yours may differ again.
The Python tutorial defines a set as “an unordered collection with no duplicate elements” and says its basic uses “include membership testing and eliminating duplicate entries”. Because the order is not fixed, the rest of this lesson prints sets of strings with sorted(). You met sorted() in Lesson 15: it returns a sorted list, so the output is the same every time.
The empty set trap: set() vs {}
Dictionaries also use curly brackets. Empty brackets make a dictionary, not a set:
basket = {}
print(type(basket))
basket = set()
print(type(basket))
print(basket, len(basket))
<class 'dict'>
<class 'set'>
set() 0
The tutorial says it directly: “to create an empty set you have to use set(), not {}”. Python even prints an empty set as set(). If you forget, adding an item fails, because a dictionary has no add() method:
basket = {}
basket.add("Pen")
Traceback (most recent call last):
File "/home/learner/python-course/err1_add_to_dict.py", line 2, in <module>
basket.add("Pen")
^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'add'
This error usually means a {} should be set().
Remove duplicates with set()
set() can also turn a list (or any other collection) into a set. This is the quickest way to remove duplicates from a list:
orders = ["Pen", "Notebook", "Pen", "Ruler", "Notebook", "Pen"]
products = set(orders)
print(len(orders), "orders,", len(products), "different products")
print(sorted(products))
print(sorted(set("banana")))
6 orders, 3 different products
['Notebook', 'Pen', 'Ruler']
['a', 'b', 'n']
len(set(orders)) counts the different products in one line. A string is a collection of characters, so set("banana") gives its three different letters.
Keep the original order
A set forgets the order of the list. If the order matters, use the dictionary trick from Lesson 17: keys are unique and keep insertion order.
orders = ["Pen", "Notebook", "Pen", "Ruler", "Notebook", "Pen"]
print(list(dict.fromkeys(orders)))
['Pen', 'Notebook', 'Ruler']
dict.fromkeys(orders) creates “a new dictionary with keys from iterable” (from the Built-in Types page), and list() takes the keys back out in the order they were first seen.
Sets have no order and no indexes
Even numbers are not kept in sorted order:
codes = {10, 3, 7}
print(codes)
print(sorted(codes))
{10, 3, 7}
[3, 7, 10]
With no order, there are no positions either, so sold[0] fails:
sold = {"Pen", "Notebook", "Ruler"}
print(sold[0])
Traceback (most recent call last):
File "/home/learner/python-course/err2_set_index.py", line 2, in <module>
print(sold[0])
~~~~^^^
TypeError: 'set' object is not subscriptable
The Built-in Types page explains: sets “do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.” If you need positions, use a list, or make one with sorted(sold).
Add and remove items
A set can change after you create it. add() adds one item, and update() adds every item from a list:
cart = {"Pen", "Notebook"}
cart.add("Ruler")
cart.add("Pen")
print(sorted(cart), len(cart))
cart.update(["Eraser", "Pen", "Backpack"])
print(sorted(cart))
cart.remove("Notebook")
cart.discard("Laptop")
print(sorted(cart))
['Notebook', 'Pen', 'Ruler'] 3
['Backpack', 'Eraser', 'Notebook', 'Pen', 'Ruler']
['Backpack', 'Eraser', 'Pen', 'Ruler']
Adding "Pen" again did nothing and raised no error. update() added "Eraser" and "Backpack" and skipped the extra "Pen".
remove() and discard() both delete an item. The difference is what happens when the item is not in the set. discard("Laptop") quietly did nothing. remove() raises an error:
cart = {"Pen", "Ruler"}
cart.remove("Laptop")
Traceback (most recent call last):
File "/home/learner/python-course/err3_remove_missing.py", line 2, in <module>
cart.remove("Laptop")
~~~~~~~~~~~^^^^^^^^^^
KeyError: 'Laptop'
Use remove() when the item must be there, and discard() when a missing item is normal.
Check membership with in
in and not in from Lesson 9, Python Operators: Comparison, Logical, is vs == and Precedence work on sets just like on lists:
in_stock = {"Pen", "Notebook", "Ruler"}
print("Pen" in in_stock)
print("Laptop" in in_stock)
print("Laptop" not in in_stock)
order = ["Pen", "Laptop", "Ruler"]
for item in order:
if item in in_stock:
print(item, "- in stock")
else:
print(item, "- not available")
True
False
True
Pen - in stock
Laptop - not available
Ruler - in stock
A comment in the tutorial’s set example calls this “fast membership testing”. With thousands of items, in on a set is much faster than in on a list; Lesson 19 measures the difference.
Python set operations: union, intersection and difference
Sets really help when you compare two groups, such as the products sold on Monday and on Tuesday:
monday = {"Pen", "Notebook", "Ruler", "Eraser"}
tuesday = {"Pen", "Backpack", "Ruler", "Water bottle"}
print("Either day: ", sorted(monday | tuesday))
print("Both days: ", sorted(monday & tuesday))
print("Monday only: ", sorted(monday - tuesday))
print("Tuesday only: ", sorted(tuesday - monday))
print("Exactly one day:", sorted(monday ^ tuesday))
print(len(monday), len(tuesday))
Either day: ['Backpack', 'Eraser', 'Notebook', 'Pen', 'Ruler', 'Water bottle']
Both days: ['Pen', 'Ruler']
Monday only: ['Eraser', 'Notebook']
Tuesday only: ['Backpack', 'Water bottle']
Exactly one day: ['Backpack', 'Eraser', 'Notebook', 'Water bottle']
4 4

- Union,
a | bora.union(b): items in a, in b, or in both. - Intersection,
a & bora.intersection(b): items in both a and b. - Difference,
a - bora.difference(b): items in a but not in b. - Symmetric difference,
a ^ bora.symmetric_difference(b): items in a or b, but not in both.
monday - tuesday and tuesday - monday give different answers, so the order matters for difference. Each operation makes a new set: monday and tuesday still have 4 items each.
Methods accept a list, operators do not
The methods accept any collection, such as a list of orders:
monday = {"Pen", "Notebook", "Ruler", "Eraser"}
tuesday_orders = ["Pen", "Backpack", "Ruler", "Water bottle", "Pen"]
print(sorted(monday.union(tuesday_orders)))
print(sorted(monday.intersection(tuesday_orders)))
print(sorted(monday.difference(tuesday_orders)))
print(sorted(monday.symmetric_difference(tuesday_orders)))
['Backpack', 'Eraser', 'Notebook', 'Pen', 'Ruler', 'Water bottle']
['Pen', 'Ruler']
['Eraser', 'Notebook']
['Backpack', 'Eraser', 'Notebook', 'Water bottle']
The operators need a set on both sides. With a list on one side you get an error:
monday = {"Pen", "Notebook", "Ruler", "Eraser"}
tuesday_orders = ["Pen", "Backpack", "Ruler", "Water bottle", "Pen"]
print(monday | tuesday_orders)
Traceback (most recent call last):
File "/home/learner/python-course/err4_operator_list.py", line 3, in <module>
print(monday | tuesday_orders)
~~~~~~~^~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for |: 'set' and 'list'
The Built-in Types page describes this on purpose: the method versions “will accept any iterable as an argument”, while “their operator based counterparts require their arguments to be sets”. Fix it with monday | set(tuesday_orders) or with the method.
What can go inside a set?
Set items must be hashable. In practice that means items that cannot change: numbers, strings and tuples. The glossary says hashability “makes an object usable as a dictionary key and a set member”, so this is the same rule as for dictionary keys in Lesson 17. A tuple works:
variants = {("Pen", "Blue"), ("Pen", "Red"), ("Pen", "Blue")}
print(len(variants))
print(("Pen", "Red") in variants)
2
True
A list does not, because a list can change:
variants = {["Pen", "Blue"], ["Pen", "Red"]}
Traceback (most recent call last):
File "/home/learner/python-course/err5_list_in_set.py", line 1, in <module>
variants = {["Pen", "Blue"], ["Pen", "Red"]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
Use a tuple instead (see Lesson 16, Python Tuples and Unpacking: One-Item Tuples, Star Unpacking and Swapping). The longer message is new in Python 3.14 (listed under improved error messages); on Python 3.13 we saw only TypeError: unhashable type: 'list'. For the same reason, a normal set cannot go inside another set.
frozenset: a set that cannot change
A frozenset is a set that cannot be changed after it is made. It has in and all the operations, but no add() or remove():
weekend = frozenset({6, 7})
print(weekend)
print(7 in weekend)
print(weekend | {5})
frozenset({6, 7})
True
frozenset({5, 6, 7})
weekend = frozenset({6, 7})
weekend.add(5)
Traceback (most recent call last):
File "/home/learner/python-course/err6_frozenset_add.py", line 2, in <module>
weekend.add(5)
^^^^^^^^^^^
AttributeError: 'frozenset' object has no attribute 'add'
On Python 3.15.2 the message ends with a hint, Did you mean to use a 'set' object?, one of the improved error messages in Python 3.15. weekend | {5} worked because it makes a new frozenset and leaves weekend alone. The docs say a frozenset “is immutable and hashable”, so it “can be used as a dictionary key or as an element of another set”.
Try it yourself
Exercise 1: Unique visitors
A shop logged these visitors: ["Ali", "Sara", "Ali", "Hina", "Omar", "Sara", "Ali"]. Print how many visits there were, how many different people visited, and their names in alphabetical order.
Exercise 2: Two clubs
The chess club is {"Ali", "Sara", "Hina", "Bilal"} and the cricket club is {"Sara", "Omar", "Bilal", "Zara"}. Print who is in both clubs, who is only in the chess club, and how many people are in at least one club.
Exercise 3: What is still missing?
A student needs {"Pen", "Notebook", "Ruler", "Eraser"} and has packed ["Pen", "Ruler", "Pen", "Water bottle"]. Print the items still missing, or All packed! if nothing is missing.
Solutions
Solution 1
visitors = ["Ali", "Sara", "Ali", "Hina", "Omar", "Sara", "Ali"]
unique_visitors = set(visitors)
print(len(visitors), "visits by", len(unique_visitors), "people")
print(sorted(unique_visitors))
7 visits by 4 people
['Ali', 'Hina', 'Omar', 'Sara']
set() drops the repeated names, and sorted() puts them in alphabetical order.
Solution 2
chess = {"Ali", "Sara", "Hina", "Bilal"}
cricket = {"Sara", "Omar", "Bilal", "Zara"}
print("Both clubs:", sorted(chess & cricket))
print("Chess only:", sorted(chess - cricket))
print("All members:", len(chess | cricket))
Both clubs: ['Bilal', 'Sara']
Chess only: ['Ali', 'Hina']
All members: 6
Intersection finds the shared members, difference the chess-only ones, and the union counts each person once.
Solution 3
needed = {"Pen", "Notebook", "Ruler", "Eraser"}
packed = ["Pen", "Ruler", "Pen", "Water bottle"]
missing = needed - set(packed)
if missing:
print("Still missing:", sorted(missing))
else:
print("All packed!")
Still missing: ['Eraser', 'Notebook']
set(packed) turns the list into a set so - works, and an empty set counts as false in if, like the empty values in Lesson 8.
Common mistakes
- Using
{}for an empty set.{}is an empty dictionary, sobasket.add("Pen")givesAttributeError: 'dict' object has no attribute 'add'. Writebasket = set(). - Expecting a fixed order or using an index. The printed order can change between runs, and
sold[0]givesTypeError: 'set' object is not subscriptable. Usesorted(sold)when you need order. - Using
remove()for an item that may be missing.cart.remove("Laptop")givesKeyError: 'Laptop'. Usecart.discard("Laptop"). - Mixing a set and a list with an operator.
monday | tuesday_ordersgivesTypeError: unsupported operand type(s) for |: 'set' and 'list'. Usemonday.union(tuesday_orders)or convert withset(). - Putting lists inside a set. It gives
TypeError: cannot use 'list' as a set element (unhashable type: 'list'). Use tuples.
Frequently asked questions
How do I remove duplicates from a list in Python?
Convert it to a set and back: list(set(orders)). This loses the original order. To keep the order in which items first appeared, use list(dict.fromkeys(orders)).
What is the difference between a list and a set in Python?
A list keeps its items in order, allows duplicates and lets you read items by index. A set has no order, keeps each item once, has no indexes, and is built for fast in checks and for comparing groups.
What is the difference between remove() and discard() in a Python set?
Both delete an item from the set. If the item is not in the set, remove() raises KeyError, while discard() does nothing. The Built-in Types page describes remove() as raising KeyError “if elem is not contained in the set”, and discard() as removing the item “if it is present”.
Summary
- A set is an unordered collection with no duplicates:
{"Pen", "Ruler"}; an empty set isset(), never{}. set(a_list)removes duplicates;list(dict.fromkeys(a_list))does it and keeps the order.add()andupdate()add items;remove()raisesKeyErrorfor a missing item,discard()does not.|,&,-and^give union, intersection, difference and symmetric difference; the method versions also accept lists.- Set items must be hashable (numbers, strings, tuples), and a
frozensetis a set that cannot change.
Next lesson
Next: Lesson 19, Python List vs Tuple vs Set vs Dict: Which One to Use.
Sources
- Data Structures: Sets (Python tutorial)
- Built-in Types: Set types, set and frozenset, and dict.fromkeys() (Python docs)
- Glossary: hashable (Python docs)
- What’s New in Python 3.14: improved error messages (Python docs)
- What’s New in Python 3.15: improved error messages (Python docs)
- Python downloads page (python.org)





