Sets are unordered collections of unique elements. They provide a convenient way to work with distinct values and perform set operations.
Sets are created by enclosing comma-separated values in curly braces {}
or by using the set()
function. Let's look at some examples:
# Creating sets
set1 = {1, 2, 3}
set2 = set([3, 4, 5])
In the first example, we create a set called set1
using curly braces. In the second example, we create a set called set2
using the set()
function.
Sets do not maintain the order of elements, and they only contain unique values. Duplicate values are automatically eliminated:
# Accessing set elements
print(set1) # Output: {1, 2, 3}
print(set2) # Output: {3, 4, 5}
In this example, we print the contents of set1
and set2
to observe the unique elements in each set.
Sets provide several useful operations for working with collections of unique elements. Let's explore three common set operations:
- Union (
|
): Combines elements from multiple sets, excluding duplicates.
# Union of sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
In this example, we use the |
operator to perform the union of set1
and set2
, resulting in a new set union_set
containing all the unique elements from both sets.
- Intersection (
&
): Finds common elements between multiple sets.
# Intersection of sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
In this example, we use the &
operator to find the common elements between set1
and set2
, resulting in a new set intersection_set
containing the element 3, which is present in both sets.
- Difference (
-
): Finds the elements in one set that are not present in another set.
# Difference of sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
In this example, we use the -
operator to find the elements in set1
that are not present in set2
, resulting in a new set difference_set
containing the elements 1 and 2.