Set in Python
A set in Python is a built-in data type used to store multiple unique values in a single variable.
It is mainly used when:
- You want to avoid duplicate values
- You need fast searching
- You want to perform mathematical set operations like union and intersection
What is a Set?
A set is a collection of unique elements.
- Unordered: Items are not stored in a particular order.
- Mutable: You can add or remove elements.
- No duplicate elements: Each item appears only once.
Example:
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Output: {1, 2, 3, 4, 5}Creating a Set
s = set()
# set with element
s = {1,2,3,4}
# Duplicate values are automatically removed
s = {1,2,2,3,4}
print(s)
# {1,2,3,4}Note:
- {} creates an empty dictionary
- Use set() for an empty set
Characteristics of Set
- Unordered
- No indexing
- No duplicates
- Mutable (can be changed)
- Elements must be immutable (no list inside set)
Accessing Elements
Since sets are unordered, you cannot use index.
s = {10, 20, 30}
for item in s:
print(item)Adding Elements
add()(Add One Element)
s = {1,2,3}
s.add(4)
print(s)
# output
# {1, 2, 3, 4}2. update() (Add Multiple Elements)
s.update([5, 6, 7])
print(s)
# ouput
# {1, 2, 3, 5, 6, 7}Removing Elements
remove()
Removes an element.
Raises error if element does not exist.
s.remove(2)
print(s)
# output
# {1, 3}2. discard()
Removes an element.
Does NOT raise error if element not found.
s.discard(10)3. pop()
Get Saurabh Gandhi’s stories in your inbox
Join Medium for free to get updates from this writer.
Removes a random element.
s.pop()4. clear()
Removes all elements.
s.clear()Set Operations
Sets support mathematical operations.
- Union (
|)
- Combines both sets.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)
# ouput
# {1, 2, 3, 4, 5}2. Intersection (&)
- Common elements only.
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B)
# ouput
# {3}3. Difference (-)
- Elements in first set but not in second.
A = {1, 2, 3}
B = {3, 4, 5}
print(A - B)
# ouput
# {1, 2}4. Symmetric Difference (^)
- Elements not common in both sets.
A = {1, 2, 3}
B = {3, 4, 5}
print(A ^ B)
# ouput
# {1, 2, 4, 5}Frozen Set
- If you want an immutable set, use
frozenset().
fs = frozenset([1, 2, 3])
print(fs)Frozen sets:
- Cannot be modified
- Can be used as dictionary keys
When Should You Use a Set?
Use a set when:
- You need unique values
- You want fast lookup
- You need mathematical operations
- Order does not matter
Questions
- What is a set in Python?
- Why are sets unordered?
- Can sets contain duplicate values?
- What is the difference between remove() and discard()?
- What is the internal working of a set?
- What is a frozenset?
- Explain union, intersection, difference.








