Python set() Function
set() is a built-in function in Python used to create a mutable set.
A set is an unordered collection of unique elements, similar to the mathematical concept of a set.set() The function can create a set from other iterables and is often used for deduplication, set operations and similar scenarios.
Word meaning: set means "set" and refers to an unordered collection of unique elements in Python.
Basic syntax and parameters
Syntax format
set(iterable)
Parameter Description
- Parameter iterable:
- Type: iterable
- Description: the iterable to convert into a set.
Function description
- Return Value: Returns a mutable set.
- Special values: Called without arguments it returns an empty set
set()(Note:{}creates an empty dictionary).
Example
Example 1: creating sets
Example
Create from a list (automatically deduplicated)
lst
=
[
1
,
2
,
2
,
3
,
3
,
3
,
4
]
s
=
set
(
lst
)
(
s
)
Output: {1, 2, 3, 4}
Create from a string
s
=
set
(
"hello"
)
(
s
)
Output: {'h', 'e', 'l', 'o'}
Create from a tuple
t
=
(
1
,
2
,
3
,
2
,
1
)
s
=
set
(
t
)
(
s
)
Output: {1, 2, 3}
Create from a dictionary (keys only)
d
=
{
"a"
:
1
,
"b"
:
2
,
"c"
:
3
}
s
=
set
(
d
)
(
s
)
Output: {'a', 'b', 'c'}
Empty Collection
s
=
set
(
)
(
s
)
Output: set()
(
type
(
s
)
)
Output:
Expected output:
{1, 2, 3, 4}
{'h', 'e', 'l', 'o'}
{1, 2, 3}
{'a', 'b', 'c'}
set()
Code analysis:
- A set automatically removes duplicate elements.
- Sets are unordered, so the element order may vary.
- Note:
{}creates an empty dictionary, not an empty set.
Example 2: set operations
Example
Create two sets
A
=
{
1
,
2
,
3
,
4
}
B
=
{
3
,
4
,
5
,
6
}
Union
(
A | B
)
Output: {1, 2, 3, 4, 5, 6}
(
A.
union
(
B
)
)
Output: {1, 2, 3, 4, 5, 6}
Intersection
(
A & B
)
Output: {3, 4}
(
A.
intersection
(
B
)
)
Output: {3, 4}
Difference (A - B)
(
A - B
)
Output: {1, 2}
(
A.
difference
(
B
)
)
Output: {1, 2}
Symmetric difference
(
A ^ B
)
Output: {1, 2, 5, 6}
(
A.
symmetric_difference
(
B
)
)
Output: {1, 2, 5, 6}
Expected output:
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{3, 4}
{3, 4}
{1, 2}
{1, 2}
{1, 2, 5, 6}
{1, 2, 5, 6}
Sets support rich operations: union, intersection, difference and symmetric difference.
Python3 built-in function