I. What Is a Set
A set is a data structure in Python used to store non-duplicate elements.
Unlike lists and tuples, a set does not access elements through integer indices; instead, it organizes data by each element's hash value, and is mainly used for deduplication, membership testing, and set operations.
Example:
numbers = {1, 2, 3, 4, 5}
print(numbers)
Sets have the following characteristics:
- Unique elements: a set never keeps duplicate elements.
- Unordered semantics: a set does not guarantee the insertion order of its elements, and does not support access through integer indices.
- Elements must be hashable: unhashable objects such as lists and dictionaries cannot be stored directly.
- Mutability:
setsupports adding, removing, and modifying elements. - Set operations: supports union, intersection, difference, and symmetric difference.
- Efficient membership testing: on average, membership testing has a time complexity of O(1).
Python provides two main set types:
| Type | English Name | Mutable | Hashable | Can Be Used as a Dictionary Key |
|---|---|---|---|---|
set |
Mutable Set | Yes | No | No |
frozenset |
Frozen Set | No | Yes | Yes |
The core difference between the two is mutability.
set is suited to scenarios that require dynamically adding and removing elements, while frozenset is suited to scenarios that need an immutable set, use as a dictionary key, or nesting within other sets.
II. Creating a set
1. Creating a set with curly braces
You can use {} to create a set containing elements.
numbers = {1, 2, 3, 4, 5}
print(numbers)
print(type(numbers))
The output type:
<class 'set'>
Duplicate elements are merged automatically:
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
Only the unique elements are kept in the result.
Note: the output order of a set should not be treated as a stable data order.
2. Creating a set with set()
set() can convert an iterable into a set.
numbers = set([1, 2, 2, 3, 4])
print(numbers)
You can pass in a tuple:
data = set((10, 20, 20, 30))
print(data)
You can also pass in a string:
letters = set("hello")
print(letters)
A string is treated as a sequence of characters, so duplicate characters are removed.
3. Creating an empty set
This is a spot where Python beginners often make mistakes.
data = {}
print(type(data))
Output:
<class 'dict'>
Empty curly braces denote a dictionary, not a set.
To create an empty set you must use:
items = set()
print(type(items))
4. Using set comprehensions
A set comprehension can generate a set from an iterable.
Syntax:
{expression for item in iterable if condition}
Example:
numbers = [1, 2, 3, 4, 5, 6]
squares = {
number ** 2
for number in numbers
}
print(squares)
Adding a condition:
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {
number ** 2
for number in numbers
if number % 2 == 0
}
print(even_squares)
Set comprehensions are well suited to deduplicating data, filtering, and quickly building a collection of unique elements.
5. The difference between set() and set comprehensions
| Method | Syntax | Use Case |
|---|---|---|
| Curly braces | {1, 2, 3} |
Define a set directly |
set() |
set(iterable) |
Convert an existing iterable |
| Set comprehension | {x for x in data} |
Generate a set based on conditions |
III. Constraints on Set Elements
Elements in a set must be hashable (Hashable).
1. What Is a Hashable Object?
A hashable object has a stable hash value and supports equality comparison.
Python provides the built-in function hash():
print(hash(100))
print(hash("python"))
print(hash((1, 2, 3)))
Sets organize elements by hash value, so elements are required to satisfy the hash rules while stored.
Important rule:
If two objects are equal, their hash values must be equal.
a = 10
b = 10
print(a == b)
print(hash(a) == hash(b))
The converse does not hold: equal hash values do not necessarily mean the objects are equal.
2. Common Hashable Types
| Type | Can Be a Set Element | Notes |
|---|---|---|
int |
Yes | Integers are hashable |
float |
Yes | Floats are hashable |
bool |
Yes | Equal to some integers |
str |
Yes | Strings are immutable |
bytes |
Yes | Byte strings are immutable |
tuple |
Conditionally yes | All elements must be hashable |
frozenset |
Yes | Immutable set |
list |
No | Mutable and unhashable |
dict |
No | Mutable and unhashable |
set |
No | Mutable and unhashable |
Example:
data = {
1,
"python",
(10, 20),
frozenset({1, 2})
}
print(data)
3. Why Lists Cannot Be Set Elements
data = {
[1, 2],
[3, 4]
}
Executing this triggers:
TypeError: unhashable type: 'list'
The reason is that lists are mutable. If a list is modified, its contents and equality may change, so it is not suitable as a key in a hash table directly.
If you really need to combine multiple values into a single set element, you can use a tuple:
data = {
(1, 2),
(3, 4)
}
However, all elements inside the tuple must also be hashable.
4. Conditions for Tuples as Set Elements
The following is valid:
data = {
(1, 2),
("python", "java")
}
The following is invalid:
data = {
(1, [2, 3])
}
Because the tuple contains a list, the entire tuple is unhashable.
5. The Special Case of True, 1, and 1.0
In Python:
print(True == 1)
print(1 == 1.0)
The results are both True.
Their hash values are also the same, so they are treated as the same element in a set.
data = {True, 1, 1.0}
print(data)
print(len(data))
Only one corresponding element is retained in the set.
If the business logic requires distinguishing numeric values of different types, you should design an explicit type identifier before constructing the set, rather than relying on their surface representation.
IV. Basic Operations on Sets
1. add(): Add a Single Element
add() is used to add one element to a set.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
If the element being added already exists, the set will not create a duplicate.
numbers.add(3)
print(numbers)
add() modifies the set in place and returns None.
result = numbers.add(5)
print(result)
2. update(): Adding Elements in Bulk
update() can add elements from one or more iterables to the set.
numbers = {1, 2, 3}
numbers.update([3, 4, 5])
print(numbers)
You can pass multiple iterables at the same time:
numbers = {1, 2}
numbers.update(
[2, 3],
(3, 4),
{4, 5}
)
print(numbers)
Duplicate elements are automatically removed.
3. remove(): Removing a Specified Element
numbers = {1, 2, 3, 4}
numbers.remove(3)
print(numbers)
If the element does not exist, a KeyError is raised.
numbers.remove(10)
4. discard(): Safely Removing an Element
discard() is similar to remove(), but it does not raise an exception when the element does not exist.
numbers = {1, 2, 3}
numbers.discard(2)
numbers.discard(10)
print(numbers)
The difference between the two methods:
| Method | Element Exists | Element Does Not Exist |
|---|---|---|
remove(x) |
Removes the element | KeyError |
discard(x) |
Removes the element | Does nothing |
If you are not sure whether an element exists, using discard() is usually more convenient.
5. pop(): Randomly Remove and Return an Element
A set has no fixed last element, so pop() removes and returns an element from the set.
numbers = {10, 20, 30, 40}
item = numbers.pop()
print(item)
print(numbers)
Do not rely on pop() to remove a specific element, and do not interpret it as removing the last inserted element.
If the set is empty, calling pop() raises a KeyError.
6. clear(): Clearing the Set
numbers = {1, 2, 3}
numbers.clear()
print(numbers)
Output:
set()
clear() removes all elements, but the set object itself still exists.
7. Comparison of Basic Set Operations
| Method | Purpose | Return Value | When Element Does Not Exist |
|---|---|---|---|
add(x) |
Adds one element | None |
Not applicable |
update(iterable) |
Adds in bulk | None |
Not applicable |
remove(x) |
Removes a specified element | None |
KeyError |
discard(x) |
Safely removes an element | None |
No error |
pop() |
Removes and returns an element | An element | KeyError when the set is empty |
clear() |
Clears the set | None |
Not applicable |
V. Set Operations
One of the greatest advantages of sets is their support for set operations in the mathematical sense.
Python provides:
- Union
- Intersection
- Difference
- Symmetric Difference
- Subset
- Superset
- Disjoint
Suppose there are two sets:
```python A = {1, 2, 3, 4} B = {3, 4, 5, 6} ```1. Union: union()
A union is the set of all unique elements from both sets.
Mathematical representation:
Using |:
result = A | B
print(result)
Using the method:
result = A.union(B)
The result contains every unique element from both sets.
A union does not modify the original sets; it returns a new set.
2. Intersection: intersection()
An intersection is the set of elements that exist in both sets at the same time.
Mathematical representation:
Using &:
result = A & B
print(result)
Using the method:
result = A.intersection(B)
You can pass in multiple sets:
A = {1, 2, 3, 4, 5}
B = {2, 3, 4}
C = {3, 4, 5}
result = A.intersection(B, C)
print(result)
3. Difference: difference()
A difference is the set of elements that exist in the first set but not in the second set.
Mathematical representation:
Using -:
result = A - B
print(result)
Using the method:
result = A.difference(B)
Note that a difference is directional:
print(A - B)
print(B - A)
The two results are usually different.
4. Symmetric difference: symmetric_difference()
A symmetric difference is the set of elements that exist in only one of the sets, but not in both at the same time.
Mathematical representation:
Using ^:
result = A ^ B
print(result)
Using the method:
result = A.symmetric_difference(B)
A symmetric difference can be understood as:
the union of the two sets, minus the intersection of the two sets.
5. Comparison of set operations
| Operation | Operator | Method | Meaning |
|---|---|---|---|
| Union | \| |
union() |
All unique elements |
| Intersection | & |
intersection() |
Elements shared by both |
| Difference | - |
difference() |
Elements unique to the left side |
| Symmetric difference | ^ |
symmetric_difference() |
Elements not shared by both |
Set operations illustrated:
flowchart TD
A["Set A"] --> B["Perform set operations"]
C["Set B"] --> B
B --> D{"Operation type"}
D -->|"Union"| E["Combine all unique elements from both sides"]
D -->|"Intersection"| F["Keep elements common to both sides"]
D -->|"Difference"| G["Keep elements unique to A"]
D -->|"Symmetric difference"| H["Keep elements belonging to only one side"]
E --> I["Generate the result set"]
F --> I
G --> I
H --> I
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
6. In-place Set Operations
The operators and methods above usually return a new set.
If you need to modify the original set directly, you can use:
| Operation | In-place method | Operator |
|---|---|---|
| Union | update() |
|= |
| Intersection | intersection_update() |
&= |
| Difference | difference_update() |
-= |
| Symmetric difference | symmetric_difference_update() |
^= |
Example:
A = {1, 2, 3}
B = {3, 4, 5}
A.update(B)
print(A)
In-place intersection update:
A = {1, 2, 3, 4}
B = {3, 4, 5}
A.intersection_update(B)
print(A)
In-place difference update:
A = {1, 2, 3, 4}
B = {3, 4}
A.difference_update(B)
print(A)
In-place symmetric difference update:
A = {1, 2, 3}
B = {3, 4, 5}
A.symmetric_difference_update(B)
print(A)
7. Differences Between Operators and Methods
Both set operators and methods can perform set operations, but their parameter requirements differ.
For example:
A = {1, 2, 3}
print(A | {3, 4})
print(A.union([3, 4]))
The | operator requires the objects involved in the operation to support the corresponding set operation; methods such as union() can accept iterables.
Therefore, if the operands are iterables such as lists or tuples, you can use the method form.
VI. Checking Set Relationships
Sets not only support data operations but can also determine containment relationships between two sets.
1. issubset(): Check for Subset
If all elements of set A are present in set B, then A is a subset of B.
Mathematical notation:
Using <=:
A = {1, 2}
B = {1, 2, 3, 4}
print(A <= B)
Using the method:
print(A.issubset(B))
2. issuperset(): Check for Superset
If set A contains all elements of set B, then A is a superset of B.
Mathematical notation:
Using >=:
A = {1, 2, 3, 4}
B = {1, 2}
print(A >= B)
Using the method:
print(A.issuperset(B))
3. Proper Subsets and Proper Supersets
A proper subset requires the two sets to be unequal.
Use <:
A = {1, 2}
B = {1, 2, 3}
print(A < B)
For proper supersets, use >:
print(B > A)
If the two sets are exactly equal, then <= and >= hold, but < and > do not.
4. isdisjoint(): Determine Whether Sets Are Disjoint
If two sets have no elements in common, they are called disjoint.
A = {1, 2, 3}
B = {4, 5, 6}
print(A.isdisjoint(B))
Returning True means there is no intersection.
5. Comparison of Set Relationship Tests
| Method or Operator | Meaning | Example |
|---|---|---|
A <= B |
A is a subset of B | {1, 2} <= {1, 2, 3} |
A < B |
A is a proper subset of B | {1, 2} < {1, 2, 3} |
A >= B |
A is a superset of B | {1, 2, 3} >= {1, 2} |
A > B |
A is a proper superset of B | {1, 2, 3} > {1, 2} |
A.isdisjoint(B) |
The two have no intersection | {1, 2}.isdisjoint({3, 4}) |
Note: The <, <=, >, and >= operators for sets indicate subset and superset relationships, not the number of elements.
VII. Other Common Set Operations
1. len(): Get the Number of Elements in a Set
numbers = {1, 2, 3, 4}
print(len(numbers))
Returns the number of distinct elements in the set.
2. in: Check Whether an Element Exists
numbers = {1, 2, 3, 4}
print(2 in numbers)
print(10 in numbers)
not in can be used to check whether an element does not exist:
if 10 not in numbers:
print("元素不存在")
Membership testing is one of the most common set operations.
3. copy(): Shallow Copy a Set
numbers = {1, 2, 3}
new_numbers = numbers.copy()
new_numbers.add(4)
print(numbers)
print(new_numbers)
copy() creates a new set object.
Since sets can directly store only hashable elements, their direct elements cannot be mutable objects such as lists or dictionaries, but custom hashable objects may still have internal mutable state. Therefore, a shallow copy does not mean recursively copying all internal objects.
4. min() and max()
numbers = {10, 30, 20, 50}
print(min(numbers))
print(max(numbers))
Returns the minimum and maximum values in the set.
The prerequisite is that the elements in the set support comparison with one another.
5. sum()
numbers = {10, 20, 30}
print(sum(numbers))
Calculates the sum of the elements in the set.
6. sorted()
Sets do not have a stable insertion order. If you need an ordered result, you can use sorted():
numbers = {50, 10, 30, 20}
result = sorted(numbers)
print(result)
The return value is a list, not a set.
print(type(result))
VIII. frozenset: Immutable Sets
frozenset is an immutable set type provided by Python.
Like set:
- Elements are unique.
- Elements must be hashable.
- It supports set operations such as union, intersection, and difference.
- It supports membership tests and relationship tests.
The difference is that, once a frozenset is created, elements cannot be added or removed.
1. Creating a frozenset
Create one with frozenset():
numbers = frozenset([1, 2, 3, 4])
print(numbers)
print(type(numbers))
You can also pass in a tuple:
data = frozenset((10, 20, 30))
Create an empty immutable set:
empty = frozenset()
print(type(empty))
Note: frozenset has no corresponding curly-brace literal syntax; it must be created through the constructor.
2. frozenset Does Not Support Modification
The following operations cannot be used on a frozenset:
numbers = frozenset({1, 2, 3})
numbers.add(4)
This raises:
AttributeError: 'frozenset' object has no attribute 'add'
Likewise, the following methods are also unavailable:
numbers.remove(1)
numbers.discard(2)
numbers.pop()
numbers.clear()
numbers.update({4, 5})
The immutability of frozenset is a constraint of the type itself.
3. frozenset Supports Set Operations
A = frozenset({1, 2, 3})
B = frozenset({3, 4, 5})
print(A | B)
print(A & B)
print(A - B)
print(A ^ B)
These operations do not modify the original sets.
The results are also usually frozenset.
4. frozenset Supports Relationship Tests
A = frozenset({1, 2})
B = frozenset({1, 2, 3})
print(A <= B)
print(B >= A)
print(A < B)
Like an ordinary set, it supports subset, superset, and disjointness tests.
5. Hashing Capability of frozenset
Because a frozenset does not allow its elements to be modified, then as long as its elements are hashable, it is itself hashable as well.
permissions = frozenset({
"read",
"write"
})
print(hash(permissions))
Therefore, a frozenset can serve as:
- A dictionary key.
- An element of an ordinary set.
- An element of another
frozenset.
For example:
permission_map = {
frozenset({"read"}): "只读用户",
frozenset({"read", "write"}): "读写用户"
}
print(permission_map[frozenset({"read"})])
Nesting is also possible:
groups = {
frozenset({1, 2}),
frozenset({3, 4})
}
print(groups)
An ordinary set does not support these usages because it is not itself hashable.
6. The Boundaries of frozenset's Immutability
The elements of a frozenset must be hashable, but being hashable does not mean that the internal state of every custom object is absolutely immutable.
If a custom object is hashable but an attribute involved in computing its hash changes, it can still break lookups in the enclosing set or dictionary.
Therefore, in engineering practice, prefer genuinely stable immutable objects as the elements of a frozenset.
IX. Differences Between set and frozenset
The two share most set operations, but mutability determines where each can be applied.
| Comparison Dimension | set | frozenset |
|---|---|---|
| Mutable | Yes | No |
| Hashable | No | Yes |
| Add element | add() |
Not supported |
| Bulk add | update() |
Not supported |
| Remove element | remove(), discard() |
Not supported |
| Clear set | clear() |
Not supported |
| Set operations | Supported | Supported |
| Membership test | Supported | Supported |
| Relationship checks | Supported | Supported |
| Dictionary key | Not allowed | Allowed |
| Set element | Not allowed | Allowed |
| Typical use | Dynamic deduplication, membership testing | Fixed permissions, immutable keys |
1. Convert set to frozenset
permissions = {"read", "write"}
fixed_permissions = frozenset(permissions)
print(fixed_permissions)
After conversion, the original set and the new set are different objects.
Modifying the original set will not change the already-created frozenset:
permissions.add("delete")
print(permissions)
print(fixed_permissions)
2. Convert frozenset to set
fixed = frozenset({1, 2, 3})
mutable = set(fixed)
mutable.add(4)
print(mutable)
print(fixed)
After conversion, you get a new mutable set.
3. Set conversion flow
flowchart TD
A["Existing set data"] --> B{"Do you need to modify elements?"}
B -->|"Yes"| C["Convert to set"]
B -->|"No"| D["Convert to frozenset"]
C --> E["Supports adding and removing"]
D --> F["Remains immutable"]
E --> G["Dynamic set operations"]
F --> H["Can be used as dictionary keys or set elements"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
10. Underlying Implementation of Sets: Hash Tables
Python's set and frozenset are usually implemented based on hash tables.
They use a hash lookup approach similar to that of dictionaries.
1. Hash function
A hash function converts an element into an integer hash value.
print(hash("python"))
print(hash(100))
print(hash((1, 2)))
Sets use hash values to locate elements.
2. How sets determine whether an element exists
When executing:
numbers = {1, 2, 3, 4}
print(3 in numbers)
A typical lookup process can be abstracted as:
Input element to look up
|
v
Compute element hash value
|
v
Determine candidate storage location
|
v
Check candidate location
|
v
Compare hash values and element equality
|
v
Return whether it exists
The actual implementation also needs to handle hash collisions.
3. Hash collisions
Different elements may have the same hash value, or may land in the same candidate location after hash table position calculation.
This situation is called a hash collision.
A hash table needs to find other candidate positions through mechanisms such as probing.
The specific internal implementation of Python sets is an interpreter implementation detail. In CPython, for example, sets use an open addressing approach to handle collisions.
4. Why sets cannot store duplicate elements
When adding an element, a set checks whether the new element already exists.
numbers = {1, 2, 3}
numbers.add(2)
print(numbers)
Since 2 already exists, the set will not add a second identical element.
Its logic can be abstracted as:
flowchart TD
A["Prepare to add element"] --> B["Compute hash value"]
B --> C["Find candidate position"]
C --> D{"Does an equal element already exist?"}
D -->|"Yes"| E["Do not add a new element"]
D -->|"No"| F["Insert new element"]
E --> G["End"]
F --> G
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px