Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A Python set is an unordered, mutable collection of distinct, hashable objects. Implemented under the hood as a hash table, a set enforces strict uniqueness among its elements and provides highly optimized, O(1)O(1) average-case time complexity for membership testing, insertions, and deletions. Because sets are unordered, they do not record element position or order of insertion, and therefore do not support indexing, slicing, or other sequence-like behaviors.

Initialization and Syntax

Sets can be instantiated using curly brace literals or the built-in set() constructor.

# Literal syntax (automatically deduplicates elements)
s1 = {1, 2, 2, 3, 4}  # Evaluates to {1, 2, 3, 4}


# Constructor syntax (accepts any iterable)
s2 = set([3, 4, 5, 5])  # Evaluates to {3, 4, 5}
s3 = set("hello")       # Evaluates to {'h', 'e', 'l', 'o'}


# Empty set initialization
s4 = set()  


# WARNING: {} initializes an empty dictionary, not an empty set.
empty_dict = {} 

The Hashability Constraint

Every element within a set must be hashable. An object is hashable if it has a hash value that never changes during its lifetime (requiring a __hash__() method) and can be compared to other objects (requiring an __eq__() method). Consequently, mutable data structures cannot be stored inside a set.

# Valid: Integers, strings, and tuples (immutable) are hashable
valid_set = {1, "string", (1, 2, 3)}


# Invalid: Lists and dictionaries are unhashable

# invalid_set = {1, [1, 2, 3]}  # Raises TypeError: unhashable type: 'list'
(Note: If you require a set as an element within another set, Python provides frozenset, an immutable and therefore hashable variant of a set).

Mutation Methods

Sets provide specific methods for in-place modification.
s = {1, 2, 3}


# Insertion
s.add(4)             # Adds a single element: {1, 2, 3, 4}
s.update([4, 5, 6])  # Adds multiple elements from an iterable: {1, 2, 3, 4, 5, 6}


# Removal
s.remove(6)          # Removes 6. Raises KeyError if the element is not found.
s.discard(10)        # Removes 10 if present. Fails silently if the element is not found.
val = s.pop()        # Removes and returns an arbitrary element. Raises KeyError if empty.
s.clear()            # Removes all elements, leaving set()

Mathematical Set Operations

Python sets natively support standard mathematical set operations, accessible via both operator overloading and explicit method calls. Operators require both operands to be sets, whereas methods accept any iterable.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}


# Union: Elements present in either set
a | b                # {1, 2, 3, 4, 5, 6}
a.union(b)


# Intersection: Elements present in both sets
a & b                # {3, 4}
a.intersection(b)


# Difference: Elements in 'a' that are not in 'b'
a - b                # {1, 2}
a.difference(b)


# Symmetric Difference: Elements in exactly one set, but not both
a ^ b                # {1, 2, 5, 6}
a.symmetric_difference(b)

Relational Operations

Sets support comparison operators to evaluate subsets, supersets, and disjointedness.
a = {1, 2, 3, 4}
c = {1, 2}


# Subset evaluation
c <= a               # True (Equivalent to c.issubset(a))
c < a                # True (Proper subset: c is a subset of a, and c != a)


# Superset evaluation
a >= c               # True (Equivalent to a.issuperset(c))
a > c                # True (Proper superset)


# Disjoint evaluation (True if sets share zero elements)
a.isdisjoint({7, 8}) # True
Master Python with Deep Grasping Methodology!Learn More