Sets
Sets
Set is a collection of unique and unordered elements. Sets are useful for eliminating duplicates from a list or performing set operations such as union, intersection, and difference.
Here are some basic operations that can be performed on sets in Python:
Creating a set:
You can create a set by enclosing a list of elements in curly braces {}, or by using the set() function, like this:
# Create a set using curly braces
my_set = {1, 2, 3}
# Create a set using the set() function
my_set = set([1, 2, 3])
Adding elements to a set:
You can add elements to a set using the add() method, like this:
# Add an element to the set
my_set.add(4)
In this example, we add element 4 to the set using the add() method.
Removing elements from a set:
You can remove elements from a set using the remove() method, like this:
# Remove an element from the set
my_set.remove(2)
In this example, we remove element 2 from the set using the remove() method.
Performing set operations:
You can perform set operations such as union, intersection, and difference using the union(), intersection(), and difference() methods, like this:
# Create two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Perform a union operation
union_set = set1.union(set2)
# Perform an intersection operation
intersection_set = set1.intersection(set2)
# Perform a difference operation
difference_set = set1.difference(set2)
In this example, we create two sets, set1 and set2, and then perform a union operation to create a new set union_set that contains all the unique elements from both sets. We also perform an intersection operation to create a new set intersection_set that contains only the elements that are common to both sets, and a difference operation to create a new set difference_set that contains only the elements that are unique to set1.
Sets are a powerful tool for performing operations on collections of unique and unordered elements in Python. With sets, you can easily eliminate duplicates from a list, perform set operations such as union, intersection, and difference, and perform other advanced operations on collections of elements.