Python3 Sets
A set is a built-in container type in Python used to store multiple unique elements.
Sets have the following characteristics:
- **No duplicate elements:** identical elements are kept only once.
- **Unordered:** elements have no fixed order and cannot be accessed by index.
- **Elements must be hashable:** they can include integers, strings, tuples and other qualifying objects, but cannot directly include unhashable objects such as lists and dictionaries.
- **Set operations supported:** union, intersection, difference, symmetric difference and more.
- **Mutable:** ordinary
setsupports adding and removing elements.
Sets are often used for deduplication, membership testing and comparing multiple data sets.
Create a collection
You can use curly braces {} to create a non-empty set, with elements separated by commas; you can also use set() to create a set from an iterable.
Syntax format:
set_name = {value1, value2, value3}
set_name = set(iterable)
For example:
Example
Create a set with curly braces
set1
=
{
1
,
2
,
3
,
4
}
Create a set from a list with set()
set2
=
set
(
[
4
,
5
,
6
,
7
]
)
Create a set from a string
set3
=
set
(
"hello"
)
(
sorted
(
set1
)
)
(
sorted
(
set2
)
)
(
sorted
(
set3
)
)
Execution result:
[1, 2, 3, 4]
[4, 5, 6, 7]
['e', 'h', 'l', 'o']
As you can see,set("hello") Duplicate letters are automatically removed l。
**Note:** To create an empty set you must use set(); you cannot use {}, because {} which represents an empty dictionary.
empty_set = set() # 空集合
empty_dict = {} # 空字典
print(type(empty_set))
print(type(empty_dict))
Execution result:
Sets deduplicate automatically
Elements in a set are never duplicated, so you can use set() to deduplicate iterables such as lists.
Example
numbers
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_numbers
=
set
(
numbers
)
(
sorted
(
unique_numbers
)
)
Execution result:
[1, 2, 3, 4, 5]
Note that after converting to a set, the original order of the elements is not guaranteed.
If you need to deduplicate a list while preserving its original order, you can use:
numbers = [3, 1, 2, 3, 2, 4]
result = list(dict.fromkeys(numbers))
print(result)
Execution result:
[3, 1, 2, 4]
The above order-preserving deduplication requires the elements to be usable as dictionary keys and applies to Python 3.7 and above.
Type restrictions on set elements
Elements in a set must be hashable objects.
Common hashable objects include integers, floats, strings and tuples whose every member is hashable.
my_set = {1, 3.14, "Python", (1, 2)}
print(len(my_set))
Execution result:
4
Lists, dictionaries and ordinary sets are usually unhashable and cannot be used directly as set elements.
my_set = {[1, 2], [3, 4]}
# TypeError: unhashable type: 'list'
If you need to use one set as an element of another set, you can use the immutable set frozenset。
Set Operations
Python sets support common mathematical set operations such as union, intersection, difference and symmetric difference.
Suppose there are two sets:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
The common operators are as follows:
| Operation | operator | Method | Description |
|---|---|---|---|
| Union | \| |
union() |
All elements in both sets, with duplicates removed |
| Intersection | & |
intersection() |
Elements belonging to both sets |
| Difference | - |
difference() |
Elements in the first set but not in the second |
| Symmetric difference | ^ |
symmetric_difference() |
Elements belonging to only one of the sets |
Example
a
=
{
1
,
2
,
3
,
4
}
b
=
{
3
,
4
,
5
,
6
}
Union
(
"Union:"
,
sorted
(
a | b
)
)
Intersection
(
"Intersection:"
,
sorted
(
a & b
)
)
Difference
(
"Difference:"
,
sorted
(
a - b
)
)
Symmetric difference
(
"Symmetric difference:"
,
sorted
(
a ^ b
)
)
Execution result:
并集: [1, 2, 3, 4, 5, 6]
交集: [3, 4]
差集: [1, 2]
对称差集: [1, 2, 5, 6]
**Note:** Difference is directional, soa - b The difference between b - a usually produce different results.
Besides operators, you can also use set methods:
a.union(b)
a.intersection(b)
a.difference(b)
a.symmetric_difference(b)
These methods return a new set and do not modify the original set directly.
Set operators usually require both operands to be sets; the corresponding methods may accept iterables such as lists and tuples depending on the method.
Set comprehension
Like list comprehensions, Python also supports set comprehensions, which create sets with concise syntax.
Basic syntax:
{expression for item in iterable if condition}
Whereif condition is an optional condition.
Example
Generate the set of squares from 1 to 5
squares
=
{
x * x
for
x
in
range
(
1
,
6
)
}
(
sorted
(
squares
)
)
Filter specified characters out of a string
letters
=
{
x
for
x
in
"abracadabra"
if
x
not
in
"abc"
}
(
sorted
(
letters
)
)
Execution result:
[1, 4, 9, 16, 25]
['d', 'r']
Set comprehensions also remove duplicate elements automatically.
Basic set operations
1. Adding elements
You can use the add() method adds an element to a set.
Syntax format:
s.add(x)
If the element already exists, the set does not change and no error is raised.
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
thisset.
add
(
"Facebook"
)
thisset.
add
(
"Google"
)
Already exists, so it is not added again
(
sorted
(
thisset
)
)
Execution result:
['Facebook', 'Google', 'Runoob', 'Taobao']
If you need to add several elements at once, you can use update()。
Syntax format:
s.update(iterable1, iterable2, ...)
update() can accept one or more iterables and add their elements to the current set.
Example
thisset
=
{
1
,
2
,
3
}
Add the elements of a list
thisset.
update
(
[
4
,
5
]
)
Add elements from several iterables at the same time
thisset.
update
(
(
6
,
7
)
,
{
8
,
9
}
)
(
sorted
(
thisset
)
)
Execution result:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
**Note:** If a dictionary is passed to update() , it is the dictionary's keys that are added, not its values.
s = {1, 2}
s.update({"a": 10, "b": 20})
print(sorted(s, key=str))
Output result:
[1, 2, 'a', 'b']
If you want to add the dictionary's values, you can use dict.values(), provided those values can be used as set elements.
2. Removing elements
Sets provide deletion methods such as remove()、discard() and pop() .
The remove() method
remove() is used to delete a specified element. If the element does not exist, it raises KeyError exception.
Syntax format:
s.remove(x)
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
thisset.
remove
(
"Taobao"
)
(
sorted
(
thisset
)
)
The following operation raises KeyError
thisset.
remove
(
"Facebook"
)
Execution result:
['Google', 'Runoob']
Traceback (most recent call last):
...
KeyError: 'Facebook'
The discard() method
discard() is also used to delete a specified element, but if the element does not exist, no exception is raised.
Syntax format:
s.discard(x)
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
thisset.
discard
(
"Facebook"
)
Does not exist, no error
thisset.
discard
(
"Taobao"
)
(
sorted
(
thisset
)
)
Execution result:
['Google', 'Runoob']
The pop() method
pop() is used to remove and return an arbitrary element from the set.
Syntax format:
s.pop()
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
,
"Facebook"
}
Remove an element
removed
=
thisset.
pop
(
)
(
"The removed element belongs to the original set:"
,
removed
in
{
"Google"
,
"Runoob"
,
"Taobao"
,
"Facebook"
}
)
(
"Number of remaining elements:"
,
len
(
thisset
)
)
Execution result:
移除的元素属于原集合: True
剩余元素个数: 3
Note:pop() is not a random sampling function, nor does it delete the first element of the set. Sets have no fixed order, so you cannot predict which element it will return.
If the set is empty, calling pop() will throw KeyError exception.
Comparison of deletion methods
| Method | Purpose | When the element does not exist |
|---|---|---|
remove(x) |
Delete a specified element | Raises KeyError |
discard(x) |
Delete a specified element | No error |
pop() |
Remove and return an arbitrary element | An empty set raises KeyError |
3. Count the elements of a set
You can use the len() function gets the number of elements in a set.
Syntax format:
len(s)
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
(
len
(
thisset
)
)
thisset.
add
(
"Google"
)
(
len
(
thisset
)
)
Execution result:
3
3
Because a set does not keep duplicate elements, adding "Google" again leaves the number of elements unchanged.
4. Clear a set
You can use the clear() method removes all elements from a set.
Syntax format:
s.clear()
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
thisset.
clear
(
)
(
thisset
)
(
len
(
thisset
)
)
Execution result:
set()
0
What is output here set() represents an empty set.
5. Check whether an element is in a set
You can use the in and not in operator checks whether an element belongs to a set.
Syntax format:
x in s
x not in s
Example
thisset
=
{
"Google"
,
"Runoob"
,
"Taobao"
}
(
"Runoob"
in
thisset
)
(
"Facebook"
in
thisset
)
(
"Facebook"
not
in
thisset
)
Execution result:
True
False
True
Sets are usually implemented with hash tables, so membership testing is generally efficient, with average time complexity O(1), though it may degrade in the worst case.
6. Check subsets, supersets and disjoint sets
Besides union, intersection and other operations, Python also supports checking the inclusion relationship between two sets.
Common methods are as follows:
| Method | Purpose |
|---|---|
issubset() |
Check whether the current set is a subset of the specified set |
issuperset() |
Check whether the current set contains all elements of the specified set |
isdisjoint() |
Check whether two sets have no common elements |
Example
a
=
{
1
,
2
}
b
=
{
1
,
2
,
3
,
4
}
c
=
{
5
,
6
}
(
a.
issubset
(
b
)
)
(
b.
issuperset
(
a
)
)
(
a.
isdisjoint
(
c
)
)
You can also use comparison operators
(
a
<=
b
)
Subset
(
a
<
b
)
Proper subset
(
b
=
a
)
Superset
Execution result:
True
True
True
True
True
True
<= and >= allow the two sets to be equal;< and > then denote a proper subset and a proper superset respectively, requiring the two to be unequal.
The immutable set frozenset
Besides the ordinary set set, Python also provides the immutable set frozenset。
Both have unique elements and no fixed order, but frozenset cannot have elements added or removed after creation.
You can use the frozenset() Create an immutable set.
Example
a
=
frozenset
(
[
1
,
2
,
3
,
3
]
)
(
sorted
(
a
)
)
(
type
(
a
)
)
frozenset supports set operations
b
=
frozenset
(
[
3
,
4
,
5
]
)
(
sorted
(
a | b
)
)
(
sorted
(
a & b
)
)
Execution result:
[1, 2, 3]
[1, 2, 3, 4, 5]
[3]
frozenset Not supported add()、remove()、update() and other modifying methods.
Because frozenset can itself be used as a hashable object, so it can also be an element of another set.
nested_set = {
frozenset({1, 2}),
frozenset({3, 4})
}
print(len(nested_set))
Execution result:
2
An ordinary set cannot be used directly as an element of another set, but frozenset can.
Notes on using sets
When using Python sets, keep the following points in mind:
- **Sets have no fixed order:** do not rely on
print(set)'s element ordering, and do not access sets by subscript. - **Elements cannot be duplicated:** adding the same element repeatedly does not increase the set's size.
- **Elements must be hashable:** unhashable objects such as lists and dictionaries cannot be used directly as set elements.
- **set() accepts iterables:** for example strings, lists and tuples; when a dictionary is passed, its keys are used.
- **Sets are iterable:** you can use a
forloop to access the elements, but the traversal order should not be used as business logic. - **Sets do not support indexing and slicing:** you cannot use
s[0]ors[1:3]。 - **Watch equality:** for example
Trueand1are considered equal in a set and cannot be stored as two different elements.
If you need to display the elements of a set in a fixed order, you can use sorted(). But if the set contains mixed types that cannot be compared with each other, sorting directly may raise TypeError。
Complete list of built-in set methods
The following is a list of commonly used built-in methods of Python sets.
| Method | Description |
|---|---|
| add() | Add an element to the set; if it already exists, do nothing. |
| clear() | Remove all elements from the set. |
| copy() | Return a shallow copy of the set. |
| difference() | Return the difference, without modifying the original set. |
| difference_update() | Modify the current set directly, removing elements that also exist in other iterables. |
| discard() | Remove a specified element; no error if it does not exist. |
| intersection() | Return the intersection, without modifying the original set. |
| intersection_update() | Modify the current set directly, keeping only elements shared with the specified iterable. |
| isdisjoint() | Check whether two sets have no common elements. |
| issubset() | Check whether the current set is a subset of the specified set. |
| issuperset() | Check whether the current set is a superset of the specified set. |
| pop() | Remove and return an arbitrary element; an empty set raises KeyError. |
| remove() | Remove a specified element; raises KeyError if it does not exist. |
| symmetric_difference() | Return the symmetric difference, i.e. elements present in only one of the two sets. |
| symmetric_difference_update() | Modify the current set directly so that it keeps only elements not shared with the specified set. |
| union() | Return the union, without modifying the original set. |
| update() | Add the elements of one or more iterables to the current set. |
| len() | A built-in function that returns the number of elements in a set. |
Note:len() is a Python built-in function, not a method of the set object itself.
In addition, set methods ending with _update() usually modify the original set directly and return None; whereas union()、intersection() and similar methods return a new set.
Summary
Python sets are mainly used to store unique data and support efficient membership testing and common set operations.
In real development, the most common uses of sets include:
- Deduplicating repeated data in a list.
- Checking whether an element exists.
- Finding the intersection, union and difference of two data sets.
- Comparing the inclusion relationship between two sets.
- Use
frozensetStoring sets that do not need to be modified.
If you need to access data by index or preserve insertion order, you should generally prefer other data structures such as lists; if you need deduplication, set operations or fast membership testing, sets are preferable.