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:
1# Creating a set using curly braces
2fruits = {"apple", "banana", "cherry"}
3print(fruits)
4# Output: {'cherry', 'banana', 'apple'}
5
6# Creating a set using the set() function
7colors = set(["red", "green", "blue"])
8print(colors)
9# Output: {'red', 'blue', 'green'}
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:
1# Adding an element to a set
2fruits = {"apple", "banana", "cherry"}
3fruits.add("orange")
4print(fruits)
5# Output: {'cherry', 'orange', 'banana', 'apple'}
6
7# Adding multiple elements to a set
8fruits.update(["mango", "grape"])
9print(fruits)
10# Output: {'grape', 'orange', 'apple', 'cherry', 'mango', 'banana'}
Set Operations
Sets support several mathematical operations such as:
- Union (
|
orunion()
method) - Intersection (
&
orintersection()
method) - Difference (
-
ordifference()
method) - Symmetric Difference (
^
orsymmetric_difference()
method)
Example:
1A = {1, 2, 3, 4}
2B = {3, 4, 5, 6}
3
4print(A | B) # Union
5# Output: {1, 2, 3, 4, 5, 6}
6
7print(A & B) # Intersection
8# Output: {3, 4}
9
10print(A - B) # Difference
11# Output: {1, 2}
12
13print(A ^ B) # Symmetric difference
14# Output: {1, 2, 5, 6}
In the next section, we’ll look into more operations on sets in Python.