# Set Methods in Python with Example

**Python set methods |** A set in Python is a data structure similar to the list that contains an unordered collection of unique elements. It is an iterable, mutable, and does not contain any duplicate elements.

Python language provides various set methods to perform basic data structure operations, such as adding, removing, updating, copy, etc.

It also provides methods to perform different mathematical operations like union, intersection, difference, and symmetric difference.

In this tutorial, we will discuss all the set methods provided by Python language with the help of basic syntax and examples. So, let’s understand each set method one by one.

## List of Python Set Methods

Here, we have listed all set methods in Python with example programs. They are:

- add()
- update()
- discard()
- remove()
- pop()
- clear()
- copy()
- union()
- intersection()
- difference()
- symmetric_difference()
- difference_update()
- intersection_update()
- issubset()
- issuperset()
- isdisjoint()

### 1. add():

This method adds a single element to the set. Since set is a mutable collection of data or elements, so we can easily add a new element in the set.

While adding a new element in the set, it removes duplicate elements from the set because a set consists of only unique elements. The general syntax of defining an add() function in Python is as:

my_set.add(element)

In this syntax, my_set is the name of set and element is the name of element that has to be added.

**Example 1:** Adding a single element to a set

# Python program to add a single element in the set. my_set = {1, 2, 3, 4, 5} # Adding a single element to a set using add() function. my_set.add(6) print(my_set) # Adding duplicate element to the set. my_set.add(3) print(my_set)

Output: {1, 2, 3, 4, 5, 6} {1, 2, 3, 4, 5, 6}

As you can see in this output of the code, if we added a new element 3 to an existing set that is already existing in the set, is ignored by the set.

### 2. update():

This method adds multiple elements to a set. It takes an iterable object like a string, list, tuple, or set. Instead of taking a full list, or set as an element, the update() function can also take individual elements of a list, or set and appends them to the existing set.

The basic syntax to use this method is as:

my_set.update(element(s))

In this syntax, my_set is the name of set and element(s) is the iterable object to be added. This method does not return anything.

**Example 2:**

# Python program to add multiple elements in the set. my_set = {1, 2, 3} # Adding a list of elements to a set using update() method. my_set.update([4, 5, 6, 7]) print(my_set) # Adding a tuple of elements to a set. my_set.update((8, 9, 10)) print(my_set) # Adding a set of elements into a set. my_set.update({11, 12, 13}) print(my_set)

Output: {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}

**Example 3:**

# Python program to add multiple iterable objects to a set. my_set = {1, 2} # Creating lists of elements. list1 = [3, 4] list2 = [5, 6] list3 = [7, 8] # Adding three lists of elements to a set using update() method. my_set.update(list1, list2, list3) print(my_set)

Output: {1, 2, 3, 4, 5, 6, 7, 8}

In this example, we have created a set of elements. Then, we have created lists of elements and added them to an existing set using update() method.

[adinserter block=”5″]

**Example 4:**

# Python program to add a string element to a set. my_set = {1, 2} # Adding a string to a set using update() method. my_set.update("Python") print(my_set)

Output: {1, 2, 'h', 'y', 'o', 'P', 't', 'n'}

In this example, we have added a string element to an existing set using update() method. Since string is an iterable object, so each character of a string is added as an individual element into the set.

**Example 5:**

# Python program to add multiple dictionary keys to a set. my_set = {1, 2} # Adding dictionary keys as elements to a set using update() method. my_set.update({3: "Three", 4: "Four", 5: "Five"}) print(my_set)

Output: {1, 2, 3, 4, 5}

In this example, we have added a dictionary of keys into a set. Note that if we add a dictionary to a set, only keys as elements will be added to a set.

**Example 6:**

# Python program to add multiple integer elements to a set. my_set = {1, 2} # Adding integer elements to a set using update() method. my_set.update(3, 4, 5) print(my_set)

Output: TypeError: 'int' object is not iterable

As you can see that as integer elements cannot be added through update() method because the update() method only supports iterable objects.

### 3. remove():

This method removes a specified element from the set. As a set is mutable data type in Python, so we can easily remove an element from the set. The general syntax to use this method is as:

my_set.remove(element)

In this syntax, my_set is the name of set and element is the name of an element that has to be deleted from the existing set. If the specified element is not present in the existing set, this method gives an error named KeyError.

[adinserter block=”2″]

**Example 7:**

# Python program to remove an element from the set. my_set = {"Dhanbad", "New York", "Sydney", "London"} # Removing an element from the set using remove() method. my_set.remove("Sydney") print(my_set)

Output: {'Dhanbad', 'New York', 'London'}

**Example 8:**

# Python program to remove an element from the set. my_set = {"Dhanbad", "New York", "Sydney", "London"} # Removing an element from the set that is not present. my_set.remove("New Delhi") print(my_set)

Output: KeyError: 'New Delhi'

### 4. discard():

This method removes or deletes a specified element from the set. If the specified element is not present in the set, it does not generate any error. This feature makes it differ from the remove() method. The general syntax to declare discard() method is as follows:

my_set.discard(element)

This method does not return any thing.

**Example 8:**

# Python program to remove an element from the set. my_set = {"Dhanbad", "New York", "Sydney", "London"} # Removing an element from the set using discard() method. my_set.discard("New York") print(my_set) # Removing an element that is not present in the set using discard() method. my_set.discard("Mumbai") print(my_set)

Output: {'Dhanbad', 'Sydney', 'London'} {'Dhanbad', 'Sydney', 'London'}

### 5. pop():

This method delete a random element from the set. The general syntax to declare pop() method is as:

my_set.pop()

This method does not accept anything and returns the removed element.

**Example 9:**

# Python program to remove a random element from the set. my_set = {"Dhanbad", "New York", "Sydney", "London"} # Removing a random element from the set using pop() method. removed_element = my_set.pop() print("Set elements: ", my_set) print("Removed element: ", removed_element)

Output: Set elements: {'Sydney', 'New York', 'London'} Removed element: Dhanbad

### 6. difference_update():

This method deletes all elements mentioned in a list from the existing set. The basic syntax to declare this method is as:

my_set.difference_update(list_of_elements)

In this syntax, my_set is the name of set and list_of_elements is the name of list elements that has to be removed from the existing set.

**Example 10:**

# Python program to remove a set of elements from the existing set. my_set = {"AA", "BB"} # Adding a list of elements to a set. my_set.update(["CC", "DD", "EE"]) print("Updated Set after adding: ", my_set) # Removing a list elements from the set using difference_update() method. my_set.difference_update(["AA", "BB"]) print("Updated set after removing: ", my_set)

Output: Updated Set after adding: {'DD', 'BB', 'EE', 'AA', 'CC'} Updated set after removing: {'DD', 'EE', 'CC'}

### 7. clear():

This method deletes all the elements from an existing set. It has a very basic syntax that is as:

my_set.clear()

This method does not take anything as well as return anything.

**Example 11:**

# Python program to clear all elements from a set. my_set = {"AA", "BB", "CC"} # Clearing all set elements. my_set.clear() print(my_set)

Output: set()

### 8. sorted():

Python programming language provides a built-in method named sorted() to sort a set of elements in ascending or descending order. We can only sort a similar type of data.

If a set has both integer and string, this method throws an error. The general syntax to declare sorted() method is as:

sorted(my_set, reverse = True or False)

This method sorts the set elements in ascending if the reverse is False. In case the parameter reverse is true, it sorts the set elements in descending order.

**Example 12:**

# Python program to sort elements from a set. my_set = {"BB", "CC", "AA", "DD"} print("Original set elements: ", my_set) # Arranging set elements in ascending order. sorted_elements = sorted(my_set, reverse = False) print("Sorted set elements: ", sorted_elements)

Output: Original set elements: {'BB', 'CC', 'DD', 'AA'} Sorted set elements: ['AA', 'BB', 'CC', 'DD']

**Example 13:**

# Python program to sort set elements in descending order. my_set = {4, 3, 6, 7, 1, 2, 5} print("Original set elements: ", my_set) # Arranging set elements in descending order. sorted_elements = sorted(my_set, reverse = True) print("Sorted set elements: ", sorted_elements)

Output: Original set elements: {1, 2, 3, 4, 5, 6, 7} Sorted set elements: [7, 6, 5, 4, 3, 2, 1]

As you can see in the above both example, sorting created a new set object. It does not modify the original set object.

**Example 14:**

# Python program to sort a set of mixed data types in ascending order. my_set = {4, 3, "AA", "BB", 1, 2} print("Original set elements: ", my_set) # Arranging set elements in ascending order. sorted_elements = sorted(my_set, reverse = False) print("Sorted elements: ", sorted_elements)

Output: Original set elements: {1, 2, 3, 4, 'BB', 'AA'} TypeError: '<' not supported between instances of 'str' and 'int'

### 9. copy():

Python language provides a built-in method named copy() to copy a set into another set. This method returns a copy of the set. Any modification in the original or copied set does not affect another set. The basic syntax to declare copy() method is as:

my_set.copy()

This method does not take anything.

**Example 15:**

# Python program to copy a set into another set. my_set = {10, 20, 30, 40, 50} # Copying my_set into another set. copied_set = my_set.copy() print("Copied set: ", copied_set) # Removing an element from the original set but it does not affect the copied set. my_set.remove(30) print("Original set: ", my_set)

Output: Copied set: {50, 20, 40, 10, 30} Original set: {50, 20, 40, 10}

### 10. union():

This method returns the union of two sets. The basic syntax to use union() method is as:

x.union(y)

In this syntax, x and y are the name of sets. This method returns the combination of all elements present in both sets x and y in the ascending order.

**Example 16:**

# Python program to get the union of two sets. set1 = {2, 4, 6, 8} set2 = {1, 3, 5, 7} # Getting the union of both sets. new_set = set1.union(set2) print(new_set)

Output: {1, 2, 3, 4, 5, 6, 7, 8}

### 11. intersection():

This method returns the common elements in both sets. The basic syntax to define this method is as:

set1.intersection(set2)

Here, set1 and set2 are the names of two sets.

**Example 17:**

# Python program to get intersection of two sets. set1 = {2, 3, 4, 5, 6, 7, 8} set2 = {1, 3, 4, 5, 9} # Getting the common elements of both sets. new_set = set1.intersection(set2) print("Common elements: ", new_set)

Output: Common elements: {3, 4, 5}

### 12. difference():

This method returns the difference of two sets. The general syntax to declare the difference() method in Python is as:

set1.difference(set2)

In this syntax, set1 and set2 are the name of two sets. The difference() method returns a set of elements present in the set1 but not present in the set2. This operation is asymmetrical because it produces the different results depending on which set is placed as set1.

**Example 18:**

# Python program to get the difference of two sets. my_set1 = {10, 20, 30, 40, 50, 60} my_set2 = {40, 50, 60, 70, 80, 90} # Getting the difference of both sets. new_set = my_set1.difference(my_set2) print("Difference: ", new_set) new_set2 = my_set2.difference(my_set1) print("Difference:", my_set2)

Output: Difference: {10, 20, 30} Difference: {80, 50, 70, 40, 90, 60}

In this example, we have used the difference() method to get the difference of two sets. The difference() method has produced the different results based on which set is the first set.

The first set is considered as the base set. In the first difference, my_set1 is the base set, whereas in the second difference, my_set2 is the base set.

### 13. symmetric_difference():

This method returns a set of symmetric difference between sets. It returns a set containing elements that are only present in one set. The general syntax to declare symmetric_difference() is as:

set1.symmetric_difference(set2)

**Example 19:**

# Python program to get the symmetric difference of two sets. my_set1 = {1, 2, 3, 4, 5, 6} my_set2 = {4, 5, 6, 7, 8, 9} # Getting the difference of both sets. new_set = my_set1.symmetric_difference(my_set2) print("Difference: ", new_set) new_set2 = my_set2.symmetric_difference(my_set1) print("Difference:", new_set2)

Output: Difference: {1, 2, 3, 7, 8, 9} Difference: {1, 2, 3, 7, 8, 9}

As you can see that the symmetric_difference() method produces the same result irrespective of the base set.

### 14. issubset():

This method is used to check a set is a subset of another set. The general syntax to declare issubset() method is as:

set1.issubset(set2)

Here, set1 and set2 are name of two sets. The issubset() method returns true value if set1 is the subset of set2. Otherwise, it returns false value. This operation is asymmetrical, and the returned value changes if we change base set.

**Example 20:**

# Python program to check a set is a subset of another set. my_set1 = {1, 2, 3, 4, 5, 6} my_set2 = {1, 2, 3, 4} # Checking a set is a subset of another set. result = my_set1.issubset(my_set2) print(result) result = my_set2.issubset(my_set1) print(result)

Output: False True

### 15. issuperset():

This method is used to check a set is a superset of another set. The general syntax to declare issuperset() method is as:

set1.issuperset(set2)

Here, set1 and set2 are name of two sets. The issuperset() method returns true value if set1 is the superset of set2. Otherwise, it returns false value. This operation is asymmetrical, and the returned value changes if we change base set.

**Example 21:**

# Python program to check a set is a superset of another set. my_set1 = {1, 2, 3, 4, 5, 6} my_set2 = {1, 2, 3, 4} # Checking a set is a superset of another set. result = my_set1.issuperset(my_set2) print(result) result = my_set2.issuperset(my_set1) print(result)

Output: True False

In case, both sets are equal, issubset() and issuperset() methods always return true value. No matter which set is the base set, as shown in the below code.

**Example 22:**

# Python program to check a set is a superset of another set. my_set1 = {1, 2, 3, 4} my_set2 = {1, 2, 3, 4} # Checking a set is a superset of another set. result = my_set1.issuperset(my_set2) print(result) result = my_set2.issuperset(my_set1) print(result)

Output: True True

### 16. isdisjoint():

Python provides built-in method named disjoint() to check if two sets are disjoint sets. Two sets are disjoint sets if they have no common element. This method returns true value if both are disjoint sets.

Otherwise, it returns false value. The isdisjoint() method provides a symmetrical operation because the returned value does not depend on the base set.

**Example 23:**

# Python program to check two sets are disjoint sets. my_set1 = {1, 2, 3, 4} my_set2 = {1, 2, 3, 4} # Checking disjoint sets. result = my_set1.isdisjoint(my_set2) print(result) result = my_set2.isdisjoint(my_set1) print(result) my_set3 = {1, 2, 3, 4, 5} my_set4 = {6, 7, 8, 9, 10} result = my_set3.isdisjoint(my_set4) print(result) result = my_set4.isdisjoint(my_set3) print(result)

Output: False False True True

## Use of Built-in Functions with Set in Python

In Python, there are several built-in functions that we can use commonly with set to perform different set operations. They are as:

In this tutorial, we have discussed details about available set methods in Python with the help of various examples. Python

library provides many set methods to perform various common operation efficiently and effectively. Hope that you will have understood the basic points of each set method and practiced all the example programs. In the next, we will perform various different important set operations in Python with the help of examples.

Thanks for reading!!!