Sets in Python
Sets in?Python
Sets are an important data structure in Python that allows the programmer to store a collection of unique elements. In this blog post, we’ll explore sets in-depth and provide examples of how to use them in your Python code.
Creating a?Set
Creating a set is simple. You begin by enclosing a collection of elements in curly braces {}. For example, if you wanted to create a set of integers, you would write:
my_set = {1, 2, 3, 4, 5}
Note that sets are unordered, so the elements are not guaranteed to be in any particular order.
You can also create a set from a list or tuple using the set() function. For example:
my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)
Adding and Removing?Elements
One of the benefits of using a set is that it allows you to easily add and remove elements. To add an element to a set, you use the add() method, like so:
my_set = {1, 2, 3}
my_set.add(4)
To remove an element from a set, you use the remove() method, like so:
领英推荐
my_set = {1, 2, 3, 4}
my_set.remove(4)
Set Operations
Sets support a number of operations that allow you to manipulate them in various ways. Here are some of the most commonly used set operations:
Union
The union of two sets is a new set that contains all the unique elements from both sets. You can perform a union using the | operator or the union() method. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 | set2
Intersection
The intersection of two sets is a new set that contains only the elements that are common to both sets. You can perform an intersection using the & operator or the intersection() method. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 & set2
Difference
The difference of two sets is a new set that contains only the elements from the first set that are not in the second set. You can perform a difference using the - operator or the difference() method. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 - set2
Subset
You can check if one set is a subset of another set using the <= operator or the issubset() method. For example:
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
set1 <= set2