🧩 Learn how to work with sets in Python — an unordered collection of unique, immutable elements.
Sets are powerful for tasks like removing duplicates, performing mathematical set operations (union, intersection, difference), and checking membership efficiently.
A set is an unordered collection of unique items. It supports:
- Membership testing (
in) - Iteration
- Mathematical operations like union, intersection, and difference
- Elements must be immutable (e.g., numbers, strings, tuples)
- Elements are not duplicated
- Order of elements is not guaranteed
skills = {'Python programming', 'Databases', 'Software design'}🔸 You can also create a set from an iterable:
chars = set('letter') # {'l', 'e', 't', 'r'}{} – it creates an empty dictionary, not a set.
empty_set = set()Since sets are unordered, you cannot access elements by index.
🔹 Use a for loop or in operator:
for skill in skills:
print(skill)print('Python programming' in skills) # TrueUse .add() to insert a new element.
skills.add('Problem solving')🔸 If the element already exists, no error is raised and nothing changes.
There are several methods to remove elements based on your needs:
| Method | Behavior |
|---|---|
.remove(x) |
Removes x, raises KeyError if missing |
.discard(x) |
Removes x, no error if missing |
.pop() |
Removes and returns an arbitrary element |
.clear() |
Removes all elements |
skills.remove('Databases') # May raise KeyError
skills.discard('Java') # Safe removal
skills.pop() # Remove random item
skills.clear() # Empty the setReturns a new set containing all elements from both sets.
set1 = {'Python', 'Java'}
set2 = {'C++', 'JavaScript'}
combined = set1 | set2
# OR
combined = set1.union(set2)🔸 .union() accepts any iterable, while | only works with sets.
Returns elements common to all sets.
s1 = {'Python', 'Java'}
s2 = {'Java', 'C++'}
common = s1 & s2 # {'Java'}Returns elements in the first set that are not in the second.
s1 = {'Python', 'Java'}
s2 = {'Java', 'C++'}
diff = s1 - s2 # {'Python'}Returns elements present in either set but not both.
s1 = {'Python', 'Java'}
s2 = {'Java', 'C++'}
result = s1 ^ s2 # {'Python', 'C++'}Check if all elements of one set are in another.
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # True
print(a <= b) # True
print(a < b) # True (proper subset)Check if a set contains all elements of another.
print(b.issuperset(a)) # True
print(b >= a) # True
print(b > a) # True (proper superset)Two sets are disjoint if they have no elements in common.
set1 = {1, 2}
set2 = {3, 4}
print(set1.isdisjoint(set2)) # TrueCreate sets using concise syntax.
{expression for element in iterable if condition}tags = {'Django', 'Pandas', 'Numpy'}
lower_tags = {tag.lower() for tag in tags}numbers = {1, 2, 3, 4, 5}
evens = {n for n in numbers if n % 2 == 0}To make a set immutable, wrap it in frozenset().
skills = frozenset({'Python', 'SQL'})🔸 Attempting to modify will raise an error:
skills.add('Git') # ❌ AttributeError| Function | Description |
|---|---|
len() |
Get number of elements |
in |
Check for membership |
set() |
Convert to a set |
skills = {'Problem solving', 'Design', 'Python'}
print(len(skills)) # Output: 3
print('Design' in skills) # True- Order is not preserved – don’t rely on element position.
- Duplicates are removed automatically when creating or updating a set.
- Use
set()with lists/tuples to easily remove duplicates. frozensetis useful for keys in dictionaries or as elements in other sets.- Use
set.intersection()over&if working with non-set iterables.
🎉 Congratulations! You now have a solid understanding of Python Sets — including how to define them, perform set operations, and use them effectively in real-world scenarios.
Next up: