A set in Python is a collection of unique elements. It is used when you want to store non-duplicate values.
Sets are:
set_name = {elements}
numbers = {1, 2, 3, 4}
names = {"Amit", "Rahul", "Priya"}
s = set()
👉 {} creates a dictionary, not a set.
Sets do not support indexing or slicing.
numbers = {1, 2, 3}
for n in numbers:
print(n)
add()numbers = {1, 2}
numbers.add(3)
print(numbers)
update()numbers.update([4, 5])
remove()numbers.remove(2)
discard()numbers.discard(10)
pop()numbers.pop()
👉 Removes a random element
|)a = {1, 2}
b = {2, 3}
print(a | b)
Output
{1, 2, 3}
&)print(a & b)
Output
{2}
-)print(a - b)
Output
{1}
^)print(a ^ b)
Output
{1, 3}
print(2 in {1, 2, 3})
print(5 not in {1, 2, 3})
A frozen set is an immutable version of a set.
fs = frozenset([1, 2, 3])
👉 Cannot be modified
| Function | Description |
|---|---|
len() |
Number of elements |
max() |
Maximum value |
min() |
Minimum value |
sum() |
Sum of elements |
a = {1, 2, 3}
b = {2, 3, 4}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
A set is a collection of unique elements
Created using {} or set()
Supports:
Does not support indexing
Useful for removing duplicates and performing set operations