Python Sets
Learn about sets in Python - unordered collections of unique items.
Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Sets are written with curly brackets.
Example
thisset = {"apple", "banana", "cherry"}
print(thisset)Note: Set items are unchangeable, but you can remove and add items.
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)Get the Length of a Set
To determine how many items a set has, use the len() function.
Example
thisset = {"apple", "banana", "cherry"}
print(len(thisset))Set Items - Data Types
Set items can be of any data type:
Example
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}A set can contain different data types:
Example
set1 = {"abc", 34, True, 40, "male"}type()
From Python's perspective, sets are defined as objects with the data type 'set':
Example
myset = {"apple", "banana", "cherry"}
print(type(myset))The set() Constructor
It is also possible to use the set() constructor to make a set.
Example
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Example
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)Example
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)Add Sets
To add items from another set into the current set, use the update() method.
Example
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)Add Any Iterable
The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).
Example
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)Note: If the item to remove does not exist, remove() will raise an error.
Example
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.
Example
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)The clear() method empties the set:
Example
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)The del keyword will delete the set completely:
Example
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:
Example
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)Example
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)Note: Both union() and update() will exclude any duplicate items.
Set Algebra
Sets shine at membership tests (O(1)) and mathematical set operations.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union {1, 2, 3, 4, 5, 6}
print(a & b) # intersection {3, 4}
print(a - b) # difference {1, 2}
print(a ^ b) # symmetric diff {1, 2, 5, 6}
print(3 in a) # True -> fast membership test| Operator | Method | Meaning |
|---|---|---|
| | union | In either set |
& | intersection | In both sets |
- | difference | In first, not second |
^ | symmetric_difference | In exactly one |
Deduplicate in One Line
names = ["ann", "bob", "ann", "cara", "bob"]
unique = set(names) # {'ann', 'bob', 'cara'}
print(len(unique)) # 3Sets are unordered — you cannot index them (s[0] is an error), and iteration order is not guaranteed. An empty set is set(), because {} creates an empty dict.
Try It Yourself
Exercise 1: Find the elements common to {1,2,3,4} and {2,4,6}.
Show solution
print({1, 2, 3, 4} & {2, 4, 6}) # {2, 4}Exercise 2: Count the number of distinct words in "the cat the dog the bird".
Show solution
text = "the cat the dog the bird"
print(len(set(text.split()))) # 4Key Takeaways
- Sets are unordered collections of unique, hashable items.
- Membership testing is O(1) — much faster than a list.
- Use
|,&,-,^for set algebra. - Convert a list to a set to remove duplicates.
📘 Real-World Deep Dive
Sets are unordered collections of unique, hashable elements. They're O(1) for membership, the right tool for de-duplication, and the basis for any "did I see this before?" logic.
Real-Life Scenario
Process a stream of URLs, count unique hosts, and surface any host that appears in both a "trusted" allow-list and a "blocked" deny-list.
Real-Life Example
import re
from urllib.parse import urlparse
HOST_RX = re.compile(r"https?://([^/\s]+)")
def host_of(url: str) -> str:
return urlparse(url).hostname or ""
stream = [
"https://docs.python.org/3/library",
"https://pypi.org/project/pip",
"https://malware.example/payload",
"https://pypi.org/project/uv",
"https://docs.python.org/3/tutorial",
"https://internal.example/api",
]
trusted = {"pypi.org", "docs.python.org", "github.com"}
blocked = {"malware.example", "ads.example.com"}
hosts: set[str] = set()
conflicts: set[str] = set()
for raw in stream:
h = host_of(raw)
if not h: continue
hosts.add(h)
if h in trusted and h in blocked:
conflicts.add(h)
print("unique hosts:", len(hosts))
print("host set :", sorted(hosts))
print("conflicts :", sorted(conflicts))Expected Output
unique hosts: 5
host set : ['docs.python.org', 'internal.example', 'malware.example', 'pypi.org', '...']
conflicts : []Common mistakes
- Sets are unordered — don't rely on iteration order; sort the output if you need it stable.
- You can't put a list in a set because lists are unhashable; convert to tuple or use the underlying values.
- Set operations (
&/|/-) are O(min(len(a), len(b))); a singleinlookup is faster.
🚀 Performance & Best Practices
- Membership in a set is O(1) — use it for any "have we seen this before?" check.
set(generator)is the fastest way to deduplicate a sequence.- Frozen sets (
frozenset) are hashable, so they can be dict keys or set members.
🧪 Try It Yourself
- Add a counter
Counter[str]for host visit frequency alongside the set. - Move the trusted/blocked into JSON files and read them at startup.
- Profile
setmembership vs.listmembership over 1 M URLs.