Set Definition
A set in Python is an unordered collection of unique elements. Being unordered, sets do not record element position or order of insertion, and this allows sets to support operations like union, intersection, and difference. Sets are mutable, however, they do not support indexing or slicing due to the lack of order.
Creating a Set
Sets in Python are created using curly braces {}
or the set()
function.
Example:
Note
When creating an empty set, we should use set()
, not {}
. The latter creates an empty dictionary.
Adding Elements to a Set
You can add a single element to a set using the add()
method, and multiple elements using the update()
method.
Example:
Set Operations
Sets support several mathematical operations such as:
- Union (
|
orunion()
method) - Intersection (
&
orintersection()
method) - Difference (
-
ordifference()
method) - Symmetric Difference (
^
orsymmetric_difference()
method)
Example:
In the next section, we’ll look into more operations on sets in Python.