Set in Python
A Set is a collection used to store multiple unique values.
1. Creating a Set
numbers = {10, 20, 30, 40} print(numbers)
Output:
{10, 20, 30, 40}
Duplicate values are automatically removed:
numbers = {10, 20, 20, 30, 30} print(numbers)
Output:
{10, 20, 30}
2. Important Properties of Sets
| Property | Set |
|---|---|
| Ordered | ❌ No |
| Changeable | ✅ Yes |
| Duplicates | ❌ Not allowed |
| Indexing | ❌ Not supported |
| Slicing | ❌ Not supported |
| Mutable | ✅ Yes |
| Syntax | {} |
Note: Set elements must be hashable, so you cannot directly store a list or dictionary inside a set.
3. Creating an Empty Set
Be careful:
x = {} print(type(x))
Output:
<class 'dict'>
For an empty set, use:
x = set() print(type(x))
Output:
<class 'set'>
4. Adding Elements
add()
Adds one element.
numbers = {10, 20, 30} numbers.add(40) print(numbers)
Output:
{10, 20, 30, 40}
Adding an existing value does nothing:
numbers.add(20)
update()
Adds multiple elements.
numbers = {10, 20} numbers.update([30, 40, 50]) print(numbers)
Output:
{10, 20, 30, 40, 50}
You can update using another set:
a = {1, 2} b = {3, 4} a.update(b) print(a)
5. Removing Elements
remove()
numbers = {10, 20, 30} numbers.remove(20) print(numbers)
Output:
{10, 30}
If the element doesn't exist, remove() gives a KeyError.
discard()
numbers = {10, 20, 30} numbers.discard(50) print(numbers)
No error occurs if 50 doesn't exist.
Difference:
| Method | Element exists | Element doesn't exist |
|---|---|---|
remove() | Removes | Error |
discard() | Removes | No error |
pop()
Removes and returns an arbitrary element.
numbers = {10, 20, 30} x = numbers.pop() print(x) print(numbers)
Because sets are unordered, you should not assume which element will be removed.
clear()
Removes everything.
numbers = {10, 20, 30} numbers.clear() print(numbers)
Output:
set()
6. Set Operations
Set operations are one of the most important uses of sets.
Suppose:
a = {1, 2, 3, 4} b = {3, 4, 5, 6}
Union
Combines all unique elements.
print(a | b)
Output:
{1, 2, 3, 4, 5, 6}
Using union():
print(a.union(b))
Intersection
Returns common elements.
print(a & b)
Output:
{3, 4}
Using intersection():
print(a.intersection(b))
Difference
Elements present in a but not in b.
print(a - b)
Output:
{1, 2}
Using:
print(a.difference(b))
Reverse difference
print(b - a)
Output:
{5, 6}
Symmetric Difference
Returns elements that are in either set, but not in both.
print(a ^ b)
Output:
{1, 2, 5, 6}
Using:
print(a.symmetric_difference(b))
7. Set Relationships
issubset()
Checks whether all elements of one set exist in another.
a = {1, 2} b = {1, 2, 3, 4} print(a.issubset(b))
Output:
True
Shortcut:
print(a <= b)
issuperset()
Checks whether a set contains all elements of another set.
a = {1, 2, 3, 4} b = {1, 2} print(a.issuperset(b))
Output:
True
Shortcut:
print(a >= b)
isdisjoint()
Checks whether two sets have no common elements.
a = {1, 2} b = {3, 4} print(a.isdisjoint(b))
Output:
True
8. Checking Membership
Use in and not in.
numbers = {10, 20, 30} print(20 in numbers) print(50 in numbers)
Output:
True False
print(50 not in numbers)
Output:
True
9. Length of a Set
Use len():
numbers = {10, 20, 30, 40} print(len(numbers))
Output:
4
10. Loop Through a Set
fruits = {"apple", "banana", "mango"} for fruit in fruits: print(fruit)
The order of output is not guaranteed.
11. Set Comprehension
Similar to list comprehension.
numbers = {1, 2, 3, 4, 5} squares = {x ** 2 for x in numbers} print(squares)
Output:
{1, 4, 9, 16, 25}
With condition:
numbers = {1, 2, 3, 4, 5, 6} even = {x for x in numbers if x % 2 == 0} print(even)
Output:
{2, 4, 6}
12. Converting List to Set
This is very useful for removing duplicates.
numbers = [10, 20, 20, 30, 30, 40] unique_numbers = set(numbers) print(unique_numbers)
Output:
{10, 20, 30, 40}
13. Converting Set to List
numbers = {10, 20, 30} my_list = list(numbers) print(my_list)
14. Frozenset
A frozenset is an immutable set.
numbers = frozenset([1, 2, 3, 4]) print(numbers)
You cannot use:
numbers.add(5)
because a frozenset cannot be changed.
Set vs Frozenset
| Feature | Set | Frozenset |
|---|---|---|
| Mutable | ✅ | ❌ |
add() | ✅ | ❌ |
remove() | ✅ | ❌ |
| Set operations | ✅ | ✅ |
| Can be used as dictionary key | ❌ | ✅ |
15. Common Set Methods
| Method | Purpose |
|---|---|
add() | Add one element |
update() | Add multiple elements |
remove() | Remove element; error if absent |
discard() | Remove element; no error if absent |
pop() | Remove arbitrary element |
clear() | Remove all elements |
union() | Combine sets |
intersection() | Common elements |
difference() | Elements in one but not another |
symmetric_difference() | Elements in either but not both |
issubset() | Check subset |
issuperset() | Check superset |
isdisjoint() | Check no common elements |
copy() | Copy a set |
16. Complete Example
students = {"Ram", "Sita", "Hari", "Ram"} print(students) students.add("Gita") print(students) students.remove("Hari") print(students) print("Sita" in students) print(len(students))
The duplicate "Ram" is automatically removed.
Set vs List vs Tuple
| Feature | List | Tuple | Set |
|---|---|---|---|
| Syntax | [] | () | {} |
| Ordered | ✅ | ✅ | ❌ |
| Mutable | ✅ | ❌ | ✅ |
| Duplicates | ✅ | ✅ | ❌ |
| Indexing | ✅ | ✅ | ❌ |
| Main use | General collection | Fixed data | Unique data |
Simple rule
- List → collection where order matters
- Tuple → collection that should not change
- Set → collection of unique values