Unordered, unindexed, no duplicates โ built on hashing. The {} vs set() trap, why only immutable elements are allowed, and the full union/intersection/difference toolbox.
A Set is one of Python's built-in data types used to store a collection of items. A set is an unordered collection of unique elements. While sets share visual similarities with dictionaries (both use curly braces {}), their behavior and rules are distinct. Sets are commonly used when you need uniqueness of items, fast membership testing (in), or mathematical set operations like union, intersection, etc.
TypeError.๐ก Revision Note
- Elements inside a set โ must be immutable
- The set container itself โ is mutable
- 2D/3D sets โ not allowed (
TypeError)
๐ก Why "mutable elements not allowed"? Sets are internally implemented using hashing. Every element must be hashable (i.e., immutable) so Python can compute a fixed hash value/slot for it in memory. Lists, dicts, and sets are mutable, so they have no stable hash โ hence TypeError: unhashable type. Because memory allocation depends on calculated hash values rather than insertion order, the displayed element order appears randomized when you print a set.
In Python, curly braces {} are used by default to construct an empty dictionary, not a set. To initialize a true empty set, you must use the built-in set() constructor.
# Incorrect way to create an empty set
S1 = {}
type(S1) # <class 'dict'>
# Correct way to create an empty set
S1 = set()
type(S1) # <class 'set'>
Sets can store items of a single data type (homogeneous) or a mix of different immutable data types (heterogeneous).
# Homogeneous Set (all elements are integers)
s_homo = {1, 2, 3, 4}
# Heterogeneous Set (mixed immutable types)
S2 = {"Hello", 4.5, True}
If you pass duplicate elements during set definition, Python retains only one instance of each value โ no error is raised.
S3 = {1, 1, 2, 2, 3, 3}
print(S3) # {1, 2, 3}
S4 = {[1, 2, 3], "Hello"}
TypeError: unhashable type: 'list'
S4 = {(1, 2, 3), "Hello"} # tuple works because it's immutable
print(S4) # {'Hello', (1, 2, 3)}
S5 = {{1}, {2}}
TypeError: unhashable type: 'set'
Things to Remember
Because sets are unordered and unindexed, bracket notation like S[0] or slicing like S[0:3] cannot be used.
S1 = {1, 2, 3, 4, 5}
S1[0] # TypeError: 'set' object is not subscriptable
S1[-1] # TypeError: 'set' object is not subscriptable
S1[0:3] # TypeError: 'set' object is not subscriptable
# Correct way: access elements using a for loop
for item in S1:
print(item)
โ ๏ธ To "access" set items, loop over the set or check membership with in โ not by position.
Sets do not support item assignment either (no positional access โ no positional editing).
S1 = {1, 2, 3, 4, 5}
S1[2] = 100
TypeError: 'set' object does not support item assignment
You cannot edit an individual element directly in-place because set items are unindexed. If you convert a set to a list, edit an item, and convert it back to a set, Python creates an entirely new set object in memory rather than editing the original set in-place.
id(S1) # e.g. 2425308876360
L = list(S1) # convert set -> list
L[0] = 100 # edit the list (lists support indexing)
S1 = set(L) # convert list -> set again
id(S1) # different id (a NEW set object was created)
Python provides two main methods to add elements to an existing set:
S1 = {1, 2, 3}
# Adding a single item
S1.add(4)
print(S1) # {1, 2, 3, 4}
# Adding multiple items
S1.update([4, 6, 7])
print(S1) # {1, 2, 3, 4, 6, 7}
Important Point
.add() (and .update()) modify the set in place โ the id() of the set does not change. This confirms sets are mutable objects, unlike the re-creation that happens with S1 = set(L) above.
Python offers multiple ways to remove data from sets:
| Method | What it does |
|---|---|
del S | Deletes the entire set variable/object from memory (not a single item) |
S.remove(val) | Removes the specified element by value (error if not found) |
S.pop() | Removes and returns an arbitrary element (sets have no order) |
S.clear() | Removes all elements, leaving an empty set set() |
S1 = {10, 20, 30, 40}
# Remove specific element
S1.remove(30)
print(S1) # {10, 20, 40}
# Pop an arbitrary element
popped_val = S1.pop()
print("Popped element:", popped_val)
print("Set after pop:", S1)
# del cannot remove a single item by index (no indexing in sets)
del S1[0] # TypeError: 'set' object doesn't support item deletion
# del deletes the whole variable
del S1
S1 # NameError: name 'S1' is not defined
# Clear all elements
S2 = {1, 2, 3}
S2.clear()
print(S2) # set()
๐ก Since sets are unordered, pop() does not guarantee removing the "first" or "last" item like a list does โ it removes whatever item Python's internal hash table returns first.
S1 = {1, 2, 3, 4, 5}
S2 = {3, 4, 5, 6, 7}
S1 + S2 # TypeError: unsupported operand type(s) for +: 'set' and 'set'
S1 * 3 # TypeError: unsupported operand type(s) for *: 'set' and 'int'
Important Point
Unlike lists/strings, sets do not support + (concatenation) or * (repetition). To combine sets, use .union().
for i in S1:
print(i)
# Output order not guaranteed
1 in S1 # True โ membership test using 'in' operator
for loop works on sets just like on lists โ iterates over each element.in checks whether a value exists in the set (very fast due to hashing).S1 = {1, 2, 3, 4, 5}
len(S1) # 5
min(S1) # 1
max(S1) # 5
sum(S1) # 15
sorted(S1) # [1, 2, 3, 4, 5] -> returns a LIST
sorted(S1, reverse=True) # [5, 4, 3, 2, 1] -> returns a LIST
| Function | Purpose | Returns |
|---|---|---|
len(S) | Number of items in set | int |
min(S) | Smallest item | element |
max(S) | Largest item | element |
sum(S) | Sum of all items (numeric sets) | number |
sorted(S) | Sorted ascending | list |
sorted(S, reverse=True) | Sorted descending | list |
๐ก sorted() always returns a list, not a set โ a set has no defined order to store the sorted result in.
Sets support standard mathematical set operations: Union, Intersection, Difference, and Symmetric Difference, plus relationship checks.
S1 = {1, 2, 3, 4, 5}
S2 = {3, 4, 5, 6, 7}
| Operation | Method / Operator | Example | Result | Meaning |
|---|---|---|---|---|
| Union | .union() or | | S1.union(S2) | {1,2,3,4,5,6,7} | All unique elements from both sets |
| Intersection | .intersection() or & | S1.intersection(S2) | {3,4,5} | Elements common to both sets |
| Difference | .difference() or - | S1.difference(S2) | {1,2} | Elements in S1 but not in S2 |
| Difference (reverse) | .difference() or - | S2.difference(S1) | {6,7} | Elements in S2 but not in S1 |
| Symmetric Difference | .symmetric_difference() or ^ | S1.symmetric_difference(S2) | {1,2,6,7} | Elements in either set, but not in both |
| Disjoint check | .isdisjoint() | S1.isdisjoint(S2) | False | True if the sets have no elements in common |
| Subset check | .issubset() | S1.issubset(S2) | False | True if every element of S1 exists in S2 |
| Superset check | .issuperset() | S1.issuperset(S2) | False | True if S1 contains every element of S2 |
| Clear set | .clear() | S1.clear() | set() | Removes all elements from the set |
S1 = {1, 2, 3, 4, 5} S2 = {3, 4, 5, 6, 7}
S1 only common (both) S2 only
{1, 2} โ {3, 4, 5} โ {6, 7}
(difference) (intersection) (difference reversed)
Union = S1 only + common + S2 only = {1,2,3,4,5,6,7}
Symmetric Difference = S1 only + S2 only = {1,2,6,7}
Important Points
difference() is not symmetric โ S1.difference(S2) โ S2.difference(S1).symmetric_difference() = union โ intersection (elements not shared by both).S1 and S2 above share elements but neither fully contains the other, isdisjoint, issubset, and issuperset all return False here..clear() empties the set completely, leaving set().a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
c = {6, 7}
print(a.isdisjoint(c)) # True (no shared elements)
print(a.issubset(b)) # True (all elements of 'a' are in 'b')
print(b.issuperset(a)) # True ('b' contains all elements of 'a')
| Feature / Method | Syntax / Code | Description / Behavior |
|---|---|---|
| Empty Set Creation | S = set() | {} creates a dict; use set() for an empty set |
| Indexing Support | S[0] (Invalid) | Sets are unindexed; subscripting raises TypeError |
| Allowed Elements | Numbers, Strings, Tuples | Only immutable data types are allowed inside sets |
| Disallowed Elements | Lists, Dicts, Sets | Mutable data types trigger TypeError |
| Add Single Item | S.add(val) | Adds one item in place |
| Add Multiple Items | S.update([v1, v2]) | Adds elements from an iterable |
| Remove by Value | S.remove(val) | Removes target value |
| Pop Arbitrary Item | S.pop() | Removes and returns an arbitrary element |
| Clear Set | S.clear() | Removes all elements |
| Union | S1.union(S2) or S1 | S2 | Combines unique elements from both sets |
| Intersection | S1.intersection(S2) or S1 & S2 | Extracts common elements |
| Difference | S1.difference(S2) or S1 - S2 | Items in S1 that are not in S2 |
| Symmetric Difference | S1.symmetric_difference(S2) or S1 ^ S2 | Items in either set, but not in both |
| Disjoint Check | S1.isdisjoint(S2) | True if no overlapping elements exist |
{} (with values) or set() (empty โ never use bare {} for an empty set, that's a dict).S[0], S[0]=x, del S[0] all fail..add(x) / .update(iterable) to add (modifies in place, id() unchanged); .remove(x) / .pop() / .clear() / del S to remove.+ and * operators are not supported on sets.for loop and in (membership) work normally on sets.len(), min(), max(), sum(), sorted() (returns a list!).union, intersection, difference, symmetric_difference, isdisjoint, issubset, issuperset, clear.