A set stores unique values and ignores duplicates automatically.
Use sets when membership checks, duplicate removal, or mathematical set operations are more important than order.
Sets are powerful for comparisons: what two groups share, what one group has that another does not, and whether a value has already been seen.
A set is an unordered collection of unique items. Sets automatically remove duplicates and are highly optimized for membership testing.
empty = set() # NOT {} - that creates an empty dict!
fruits = {"apple", "banana", "mango"}
nums = {1, 2, 3, 2, 1} # duplicates removed
print(nums) # {1, 2, 3}
# From other iterables
from_list = set([1, 2, 2, 3, 3, 4])
from_str = set("hello") # {'h', 'e', 'l', 'o'}
from_range = set(range(5)) # {0, 1, 2, 3, 4}
print(type(fruits)) # <class 'set'>
print(len(fruits)) # 3
fruits = {"apple", "banana", "mango"}
# Add
fruits.add("orange")
fruits.update(["grape", "kiwi"]) # add multiple
# Remove
fruits.remove("banana") # raises KeyError if not found
fruits.discard("papaya") # safe - no error if not found
popped = fruits.pop() # removes and returns a random item
fruits.clear() # removes all items
# Check membership
colors = {"red", "green", "blue"}
print("red" in colors) # True
print("yellow" in colors) # False
Sets support mathematical operations like union, intersection, and difference.
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# Union - all items from both sets
print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b)) # same
# Intersection - items in both sets
print(a & b) # {4, 5}
print(a.intersection(b)) # same
# Difference - items in a but not b
print(a - b) # {1, 2, 3}
print(a.difference(b)) # same
# Symmetric difference - items in either but not both
print(a ^ b) # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b)) # same
# Subset and superset
x = {1, 2}
print(x.issubset(a)) # True - all of x is in a
print(a.issuperset(x)) # True - a contains all of x
print(a.isdisjoint({9, 10})) # True - no common items
| Method | Description |
|---|---|
| add(x) | Add element x |
| update(iterable) | Add multiple elements |
| remove(x) | Remove x (KeyError if missing) |
| discard(x) | Remove x (no error if missing) |
| pop() | Remove and return a random element |
| clear() | Remove all elements |
| union(s) | Return union of sets |
| intersection(s) | Return common elements |
| difference(s) | Return elements not in s |
| symmetric_difference(s) | Return elements in either but not both |
| issubset(s) | True if all elements are in s |
| issuperset(s) | True if s is a subset |
| isdisjoint(s) | True if no common elements |
| copy() | Return a shallow copy |
# frozenset is immutable - can be used as dict key
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})
# Can be used as a dict key (regular set cannot)
lookup = {frozenset([1, 2]): "pair", frozenset([3]): "single"}
# Practical: remove duplicates from a list while preserving order
def unique(lst):
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print(unique(data)) # [3, 1, 4, 5, 9, 2, 6]
0 of 2 checked
Try this next
0 of 3 completed
Do not rely on set order. Use a list if order matters, and use a set when uniqueness or membership checks matter more.
No. Set items must be hashable. Use tuples for fixed grouped values, or store an ID instead of a mutable object.
Checking membership and removing duplicates. For example, keep a seen set while processing names or IDs.
Explore 500+ free tutorials across 20+ languages and frameworks.