Python Sets

Unordered, unindexed, no duplicates โ€” built on hashing. The {} vs set() trap, why only immutable elements are allowed, and the full union/intersection/difference toolbox.

Overview

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.

Key Rules of Python Sets

๐Ÿ’ก Revision Note
๐Ÿ’ก 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.

Creating a Set

The Empty Set Trap: {} vs 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'>

Homogeneous & Heterogeneous Sets

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}

Automatic Duplicate Handling

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}

Mutable Elements Are Not Allowed Inside a Set

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

Accessing Items in a Set

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.

Editing Items in a Set

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

Workaround: convert to list, edit, convert back to set

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)

Adding Elements โ€” .add() vs .update()

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.

Deleting & Removing Items

Python offers multiple ways to remove data from sets:

MethodWhat it does
del SDeletes 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.

Set Behaviour with Operators (+, *)

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().

Looping and Membership Test

for i in S1:
    print(i)
# Output order not guaranteed

1 in S1     # True โ€” membership test using 'in' operator

Built-in Functions on Sets

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
FunctionPurposeReturns
len(S)Number of items in setint
min(S)Smallest itemelement
max(S)Largest itemelement
sum(S)Sum of all items (numeric sets)number
sorted(S)Sorted ascendinglist
sorted(S, reverse=True)Sorted descendinglist
๐Ÿ’ก sorted() always returns a list, not a set โ€” a set has no defined order to store the sorted result in.

Set Operations & Mathematical Functions

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}
OperationMethod / OperatorExampleResultMeaning
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)FalseTrue if the sets have no elements in common
Subset check.issubset()S1.issubset(S2)FalseTrue if every element of S1 exists in S2
Superset check.issuperset()S1.issuperset(S2)FalseTrue if S1 contains every element of S2
Clear set.clear()S1.clear()set()Removes all elements from the set

Visualizing Set Operations

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

Relationship Methods โ€” Another Example

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')

Quick Revision Cheat Sheet

Feature / MethodSyntax / CodeDescription / Behavior
Empty Set CreationS = set(){} creates a dict; use set() for an empty set
Indexing SupportS[0] (Invalid)Sets are unindexed; subscripting raises TypeError
Allowed ElementsNumbers, Strings, TuplesOnly immutable data types are allowed inside sets
Disallowed ElementsLists, Dicts, SetsMutable data types trigger TypeError
Add Single ItemS.add(val)Adds one item in place
Add Multiple ItemsS.update([v1, v2])Adds elements from an iterable
Remove by ValueS.remove(val)Removes target value
Pop Arbitrary ItemS.pop()Removes and returns an arbitrary element
Clear SetS.clear()Removes all elements
UnionS1.union(S2) or S1 | S2Combines unique elements from both sets
IntersectionS1.intersection(S2) or S1 & S2Extracts common elements
DifferenceS1.difference(S2) or S1 - S2Items in S1 that are not in S2
Symmetric DifferenceS1.symmetric_difference(S2) or S1 ^ S2Items in either set, but not in both
Disjoint CheckS1.isdisjoint(S2)True if no overlapping elements exist

Final Summary