Python Set Operations with Example
In this tutorial, we will perform the most common set operations in Python with the help of examples. There are the following set operations that we commonly need to perform in the set. They are:
- Add operation
- Delete operation
- Find length of a set
- Set mathematical operations
- Union
- Intersection
- Asymmetric difference
- Symmetric difference
- Finding subset and superset
- Iteration operation
- Set membership operation (Searching)
- Sorting
- Merging
- Set comparison
- Set multiplication
- Copy
Let us perform each set operation one by one with the help of various examples.
Adding Elements to a Set in Python
To add an element to a set, we use a function named add() provided by Python. Since set is an unordered collection of items, so the element which we will append may get added at any location within a set. When we will display them, we will always get a different sequence.
Example 1:
# Python program to add an element in a set. my_set = {"Java", "JavaScript", "C", "C++"} print("Original set: ", my_set) # Calling add() function to append an element into a set. my_set.add("Python") print("Updated set: ", my_set)
Output: Original set: {'JavaScript', 'Java', 'C++', 'C'} Updated set: {'JavaScript', 'Java', 'C++', 'Python', 'C'}
To add multiple element to a set, we use update() method. The general syntax of using this method is as:
my_set.update(element(s))
Here, my_set is the name of set. This method accepts an iterable object like a list, or a set and added them into the existing set object.
Example 2:
# Python program to add an element in a set. my_set = {"Python", "C"} my_list = ["Java", "JavaScript"] print("Original set: ", my_set) # Calling update() function to append multiple elements into a set. my_set.update(my_list) print("Updated set: ", my_set)
Output: Original set: {'Python', 'C'} Updated set: {'Python', 'JavaScript', 'Java', 'C'}
Removing Elements from a Set in Python
Python language offers two methods named remove() and discard() to remove an element from a set. Both of these methods perform the same operation with only one difference that if the element to be removed does not exist in the set, then the remove() method raises an error.
[adinserter block=”5″]
While, discard() method does not produce an error for the same case. The general syntax for both methods is as follows:
my_set.remove(element) my_set.update(element)
Example 3:
# Python program to remove an element from a set. my_set = {"Python", "C", "Java", "SQL"} print("Original set: ", my_set) # Calling remove() method to delete an element from a set. my_set.remove("SQL") print("Updated set: ", my_set)
Output: Original set: {'Python', 'C', 'SQL', 'Java'} Updated set: {'Python', 'C', 'Java'}
We can also delete a random element from a set using pop() method provided by Python language. The general syntax to use this method is as:
my_set.pop()
This method does not take any argument and returns the removed element. If the set is empty, then it raises an error named KeyError.
Example 4:
# Python program to remove a random element from a set. my_set = {"Python", "C", "Java", "SQL"} print("Original set: ", my_set) # Calling pop() method to delete a random element from a set. my_set.pop() print("Updated set: ", my_set)
Output: Original set: {'Python', 'Java', 'SQL', 'C'} Updated set: {'Java', 'SQL', 'C'}
If you want to delete all the elements of a set, then use the inbuilt method named clear() provided by Python language. We can also remove multiple elements from the set either using for loop or iterating over set elements, as shown in the below example code.
Example 5:
# Python program to remove multiple elements from a set. my_set = {"Python", "C", "Java", "SQL"} print("Original set: ", my_set) # Deleting elements from a set using for loop. for x in list(my_set): my_set.discard(x) print("After removing all elements: ", my_set)
Output: Original set: {'Java', 'SQL', 'Python', 'C'} After removing all elements: set()
You can remove elements from the set using for loop based on some condition.
Find Length of Set in Python
In Python, to find the length of a set, we use the inbuilt len() method. The length of a set represents the total number of elements in the set.
Example 6:
# Python program to find the length of a set. my_set = {"Python", "C", "Java", "JavaScript"} print("Set: ", my_set) # Call len() method to find the length of a set. len_set = len(my_set) print("Length of set: ", len_set)
Output: Set: {'C', 'Python', 'JavaScript', 'Java'} Length of set: 4
Python Set Mathematical Operations
We generally use set in Python to perform the mathematical operations, such as union, intersection, difference, and symmetric difference. The following subsections have a detailed explanation of each mathematical operation with the help of examples.
[adinserter block=”2″]
Set Union Operation
A union of dual sets represents a new set that contains all elements present in both sets, removing duplicate elements. It does not modify any of the existing sets.
Python provides a built-in method named union() to perform this mathematical operation. The general syntax to define this method is as:
set1.union(set2)
Here, set1 and set2 represent the name of two sets. This method returns a new set containing all elements of both set1 and set2 in an ascending order.
Example 7:
# Python program to perform union operation. my_set1 = {1, 2, 3, 4} my_set2 = {4, 5, 6, 7} # Performing union of two sets using union() method. new_set = my_set1.union(my_set2) print("Union of sets: ", new_set)
Output: Union of sets: {1, 2, 3, 4, 5, 6, 7}
As you can see in the output the union() method prints the union of two sets by removing duplicates. We can also use the | operator instead of using union() method to perform the operation. The general syntax is as:
set1 | set2
In this syntax, set1 and set2 are two sets and will be combined into a single set by using | operator.
Example 8:
# Python program to perform union operation. my_set1 = set([1, 2, 3, 4]) my_set2 = set([3, 4, 5, 6]) # Performing union of two sets using | operator. new_set = my_set1 | my_set2 print("Union of sets: ", new_set)
Output: Union of sets: {1, 2, 3, 4, 5, 6}
Set Intersection Operation
The intersection of two sets represents a new set, containing common elements of both sets in ascending order. Python provides a built-in method named intersection() that returns a set of common elements that are available in mutually sets. This method does not modify any of the existing sets.
The general syntax to use this method is as:
set1.intersection(set2)
Here, set1 and set2 represent the name of two sets. The intersection() method returns a set of common elements in ascending order that are present in both sets.
Example 9:
# Python program to perform intersection operation. my_set1 = set([1, 2, 3, 4]) my_set2 = set([3, 4, 5, 6]) # Performing intersection of two sets using intersection() method. new_set = my_set1.intersection(my_set2) print("Intersection of sets: ", new_set)
Output: Intersection of sets: {3, 4}
We can perform the same operation using & operator. Let’s take an example of it.
Example 10:
# Python program to perform intersection operation. my_set1 = set([1, 2, 3, 4]) my_set2 = set([5, 6, 3, 4]) # Performing intersection of two sets using & operator. new_set = my_set1 & my_set2 print("Intersection of sets: ", new_set)
Output: Intersection of sets: {3, 4}
Example 11:
# Python program to perform intersection operation. my_set1 = set([1, 2, 3, 4]) my_set2 = set([5, 6, 7, 8]) # Performing intersection of two sets using & operator. new_set = my_set1 & my_set2 print("Intersection of sets: ", new_set)
Output: Intersection of sets: set()
In this example, there are no common elements present in both sets. Therefore, the intersection returns an empty set, as in the above output.
Asymmetric Set Difference Operation
Set difference represents a set of elements that are present in one set but not in the other set. For example, the difference of sets set1 and set2 (set1 – set2) is a set of elements that can be present in set1 but not in set2.
In contrast, the difference of sets set2 and set1 (set2 – set1) is a set of elements that are present in set2 but not in set1. We can perform this operation using a built-in difference() method provided by Python. The basic syntax of difference() method is as:
set1.difference(set2)
Here, set1 and set2 represent the name of two sets. This method performs asymmetrical operation, meaning that it gives the different results based on which set is the base set or first set.
Example 12:
# Python program to perform difference operation. my_set1 = {10, 20, 30, 40} my_set2 = {30, 40, 50, 60} # Performing the difference of two sets using difference() method. new_set = my_set1.difference(my_set2) print("Difference of sets: ", new_set) new_set = my_set2.difference(my_set1) print("Difference of sets: ", new_set)
Output: Difference of sets: {10, 20} Difference of sets: {50, 60}
We can perform the same operation using minus (-) operator, as in the below example code.
Example 13:
# Python program to perform difference operation. my_set1 = {10, 20, 30, 40} my_set2 = {30, 40, 50, 60} # Performing the difference of two sets using minus operator. new_set = my_set1 - my_set2 print("Difference of sets: ", new_set) new_set = my_set2 - my_set1 print("Difference of sets: ", new_set)
Output: Difference of sets: {10, 20} Difference of sets: {50, 60}
Symmetric Difference of Sets
The symmetric difference between two sets set1 and set2 represents a set of elements that are not common in both sets. In other words, it gives a set of elements contained in both sets set1 and set2, except those which are common among them.
To perform this operation, Python provides a method named symmetric_difference() that gives the same result irrespective of the base set or first set. The general syntax to use this method is as:
set1.symmetric_difference(set2)
Here, set1 and set2 are two sets. This method returns a new set that contains elements found in either set1 or set2, but not in both sets. Let’s take a simple example program based on this method.
Example 14:
# Python program to perform symmetric difference operation. my_set1 = {1, 2, 3, 4} my_set2 = {3, 4, 5, 6} # Performing the symmetric difference of two sets using symmetric_difference() method. new_set = my_set1.symmetric_difference(my_set2) print("Symmetric difference of sets: ", new_set) new_set = my_set2.symmetric_difference(my_set1) print("Symmetric difference of sets: ", new_set)
Output: Symmetric difference of sets: {1, 2, 5, 6} Symmetric difference of sets: {1, 2, 5, 6}
To find the symmetric difference of two sets, we can also use ^ operator. The general format of an expression using ^ operator is as:
set1 ^ set2
Example 15:
# Python program to perform symmetric difference operation. my_set1 = {3, 4, 5, 6} my_set2 = {8, 7, 5, 6} # Performing the symmetric difference of two sets using ^ operator. new_set = my_set1 ^ my_set2 print("Symmetric difference of sets: ", new_set) new_set = my_set2 ^ my_set1 print("Symmetric difference of sets: ", new_set)
Output: Symmetric difference of sets: {3, 4, 7, 8} Symmetric difference of sets: {3, 4, 7, 8}
Finding Subsets and Superset
Python allows us to check a set is a subset or superset of another set. For example:
my_set1 = set([1, 2, 3, 4]) my_set2 = set([2, 3])
From the above example, my_set1 contains all elements of my_set2. It means that my_set2 is the subset of my_set1. We can also call them as my_set1 is superset of my_set2.
Python provides a inbuilt method named issubset() that returns true value if my_set1 is subset of my_set2. Otherwise, it returns false value. This operation is asymmetrical and the return value can change if the first set (also called base) set changes. The general format is as:
my_set1.issubset(my_set2)
Let’s take an example code.
Example 16:
# Python program to check a set is subset of another set. my_set1 = {3, 4, 5, 6, 7} my_set2 = {3, 4, 5} # Performing the issubset operation. result = my_set1.issubset(my_set2) print(result) result = my_set2.issubset(my_set1) print(result)
Output: False True
Let’s take another program to check a set is the superset of another set.
Example 17:
# Python program to check a set is superset of another set. my_set1 = {3, 4, 5, 6, 7} my_set2 = {3, 4, 5} # Performing the issuperset operation. result = my_set1.issuperset(my_set2) print(result) result = my_set2.issuperset(my_set1) print(result)
Output: True False
In case, if both sets are equal, then issubset and issuperset both always return true value. No matter which set is the base set, as in the below example code.
Example 18:
# Python program to check a set is superset of another set. my_set1 = {3, 4, 5} my_set2 = {3, 4, 5} # Performing the issuperset operation. result = my_set1.issuperset(my_set2) print(result) result = my_set2.issuperset(my_set1) print(result)
Output: True True
To check whether one set is the subset of another set, you can also use <= operator. The general representation of using it is as:
set2 <= set1
Here, set1 and set2 are two sets. This expression returns true value if set2 is the subset of set1. Otherwise, it returns false.
Example 19:
# Python program to check a set is subset of another set. my_set1 = set([3, 4, 5, 6]) my_set2 = set([4, 5]) # Performing the issubset operation. result = my_set1 <= my_set2 print(result) result = my_set2 <= my_set1 print(result)
Output: False True
To check whether one set is the superset of another set, you can also use >= operator. The general representation of using it is as:
set1 >= set2
Here, set1 and set2 are two sets. This expression returns true value if set1 is the superset of set2. Otherwise, it returns false.
Example 20:
# Python program to check a set is superset of another set. my_set1 = set([3, 4, 5, 6]) my_set2 = set([4, 5]) # Performing the issuperset operation. result = my_set1 >= my_set2 print(result) result = my_set2 >= my_set1 print(result)
Output: True False
Iteration over Sets in Python
In Python or other programming languages, iteration over a set means accessing each element of the set one by one and performing an operation or printing each element on the console.
We can use for loop to iterate over elements of a set. Since a set is an unordered collection of elements, we can not predict which order will be followed for the iteration. Let us take an example of it.
Example 21:
# Python program to iterate over elements of a set. my_list = ["Python", "Java", "JavaScript", "C", "C++"] my_set = set(my_list) # Iterating over a set using for loop. print("Iteration over set: ") for x in my_set: print(x)
Output: Iteration over set: JavaScript C++ Java Python C
Set Membership Test (Searching Operation)
To check an element exists in the set or not, use “in” or “not in” keyword. We can use “in” operator to check the membership of a particular element in the list, tuple, or set. However, we know a set is not an index based data structure, we cannot search the index of an element.
Example 22:
# Python program to search an element in a set. my_set = {"Python", "C", "Java", "JavaScript"} # Check the membership of element using in operator. print("Python" in my_set) print("C++" in my_set)
# Check the membership of element using not in operator. print("Python" not in my_set) print("C++" not in my_set)
Output: True False False True
In this tutorial, we have performed the most common set operations in Python with examples. Hope that you will have understood the basic concepts of performing Python set operations and practiced all example programs. In the next, we will get the knowledge of frozenset in Python with the help of some important examples.
Thanks for reading!!!