A complete guide to understanding Python's set data type
A set in Python is a collection of unique, unordered elements. Sets are mainly used when you want to store items without duplicates and perform mathematical set operations like union, intersection, and difference.
# Empty set (must use set(), not {})
my_set = set()
# Set with data
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'banana', 'cherry', 'apple'}
# Duplicates are removed automatically
nums = {1, 2, 2, 3, 4}
print(nums) # {1, 2, 3, 4}
fruits = {"apple", "banana"}
# Add element
fruits.add("cherry")
# Add multiple elements
fruits.update(["mango", "grape"])
# Remove element (error if not found)
fruits.remove("banana")
# Remove element safely (no error if not found)
fruits.discard("orange")
# Remove and return a random element
fruits.pop()
# Clear all elements
fruits.clear()
print(fruits) # set()
| Method | Description | Example |
|---|---|---|
set.add(x)
|
Adds element x | fruits.add("apple") |
set.update(iterable)
|
Adds multiple elements | fruits.update(["mango","grape"]) |
set.remove(x)
|
Removes element x (error if missing) | fruits.remove("apple") |
set.discard(x)
|
Removes element x (no error if missing) | fruits.discard("apple") |
set.pop()
|
Removes and returns a random element | fruits.pop() |
set.clear()
|
Removes all elements | fruits.clear() |
set.union()
|
Returns union of sets | a.union(b) |
set.intersection()
|
Returns common elements | a.intersection(b) |
set.difference()
|
Returns elements in A not in B | a.difference(b) |
set.symmetric_difference()
|
Returns elements not common to both | a.symmetric_difference(b) |
set.issubset()
|
Checks if A is subset of B | a.issubset(b) |
set.issuperset()
|
Checks if A is superset of B | a.issuperset(b) |
set.isdisjoint()
|
Checks if A and B have no elements in common | a.isdisjoint(b) |
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union → {1, 2, 3, 4, 5}
print(a & b) # Intersection → {3}
print(a - b) # Difference → {1, 2}
print(a ^ b) # Symmetric Difference → {1, 2, 4, 5}
in keyword).
# Example: Removing duplicates
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums) # {1, 2, 3, 4, 5}