Sets in Python
Sets in Python
A set is a group of elements that are not in any specific sequence. A Python set is comparable
to this mathematical description, but with the additional requirements listed below.
Defining a Set
A set can be created in two ways. First, you can define a set with the built-in set() function:
x = set(<iter>)
Output:
Output:
Output:
Set Operations
Python sets are commonly used for mathematical operations such as union, intersection,
difference, and complement, among others. We can make a set, access its elements, and
perform the following mathematical operations, as indicated below.
Creating a set
A set is formed by using the set() function or by enclosing all elements in a pair of curly braces.
Ex
Output:
When the above code is run, it yields the following result. Please take note of how the order of
the elements has altered in the final output.
Output:
When the above code is run, it yields the following result:
Output:
When the above code is run, it yields the following result:
Output:
When the above code is run, it yields the following result.
Union of Sets
The union operation on two sets yields a new set that contains all of the different elements from
both sets. In the following example, the element "Wed" appears in both collections.
Ex:
Output:
When the above code is run, it yields the following result. Please keep in mind that the outcome
contains only one "wed."
Intersection of Sets
When two sets are intersected, a new set is created that contains just the elements that are
shared by both sets. In the following example, the element "Wed" appears in both collections.
Ex:
Output:
When the above code is run, it yields the following result. Please keep in mind that the outcome
contains only one "wed."
Output:
When the above code is run, it yields the following result. Please keep in mind that the outcome
contains only one "wed."
Compare Sets
We can determine whether a given set is a subset or superset of another. Depending on the
elements in the sets, the result is True or False.
Ex:
Output:
When the above code is run, it yields the following result:
Output:
Output: