Signup/Sign In

How to Delete Elements in a Set

In this article, we will learn to delete elements in a set in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic. Let's first have a quick look over what is a set in Python.

Python Set is a built-in data type. It is a collection of unordered data values. An unordered dataset leads to unindexed values. Set values cannot be accessed using index numbers as we did in the list. Set values are immutable which means we cannot alter the values after their creation. Data inside the set can be of any type say, integer, string, or float value. For example,

Set Example

set1 = {"Ram", "Arun", "Kiran"}
set2 = {16, 78, 32, 67}
set3 = {"apple", "mango", 16, "cherry", 3}

Delete Elements in a Set

Deleting elements from a set in Python basically means removing or discarding one or multiple elements from the set. We know that set values are immutable that means the values of a set cannot be changed after its creation. However, the set itself is mutable which means we can perform add, read, and delete operations on it.

Let's look at the below methods and learn what are the different ways to delete elements from a given set.

  1. Using remove() function
  2. Using discard() function
  3. Using pop() function
  4. Using difference_update() function

1. Using remove() function

This is a built-in function provided by set in Python. It removes the given element passed as an argument from the set. It deletes only one element a time. It deletes the element only if the element exists in the set else if the element is not present in the set, the program will generate an error or an exception is raised.

Syntax

set.remove(element)

Example: Delete if the Element exists in the set

The remove() function takes one element for deletion. The program will return the updated set.

# input set
set1 = {1,5,8,12,7}

# removing '8' from the set and prints None
print(set1.remove(8))

# Updated set
print('Updated set after deletion:', set1)


None
Updated set after deletion: {1, 5, 12, 7}

Example: Delete if the element does not exist in the set

Here, we are passing a value to the remove() function for deletion. Since this value does not exist in the set. The program will generate a KeyError.

# input set
set1 = {1,5,8,12,7}

# removing '9' from the set
set1.remove(9)

# Updated set
print('Updated set after deletion:', set1)


KeyError: 9

Note: To avoid the KeyError, we should always first check if an element exists in the set or not before trying to delete that element.

2. Using discard() function

This is a built-in function provided by set in Python. It removes the given element provided as an argument from the set. The difference between discard() and remove() is that, in case of discard(), if the element does not exist in the set, the program will not generate any error and it will print the original set. Discard() can also delete multiple elements using for loop in the program. Look at the different examples below.

Syntax

set.discard(element)

Example: Delete if the element exists in the set

The discard() function takes one element for deletion. The program will return the updated set.

# input set
set1 = {1,5,8,12,7}

# removing '8' from the set and prints None
print(set1.discard(8))

# Updated set
print('Updated set after deletion:', set1)


None
Updated set after deletion: {1, 5, 12, 7}

Example: Delete if the element does not exist in the set

The discard() function takes one element for deletion that does not exist in the set. Instead of generating an error, the program will return the original set.

# input set
set1 = {1,5,8,12,7}

# removing '9' from the set
set1.discard(9)

# Updated set
print('Updated set after deletion:', set1)


Updated set after deletion: {1, 5, 7, 8, 12}

Example: Removing multiple elements by using for loop & discard() function

This code will delete multiple elements from the given input set. It takes a new list of elements that need to be deleted. Then, it iterates over the elements of the new list of elements and deletes them one by one from the set using discard(), and prints the updated set.

# original input set
set1 = {1, 5, 8, 12, 4, 32}

#new list that contains the elements to be deleted
delete = [1, 5, 4]

# Iterate over the list of elements
for ele in delete:
       # Remove element from the set
       set1.discard(ele)

print('Updated set after deletion:', set1)


Updated set after deletion: {32, 8, 12}

3. Using pop() function

This method uses built-in pop() function provided by set in Python. It removes any arbitrary element from the set. It can remove one or more elements at a time. Different elements are removed on every time program run. It does not take any argument. pop() function will generate TypeError if the given input set is empty.

Syntax

set.pop()

Example: Delete if the set is not empty

The below example using pop() function. It returns the arbitrary deleted elements and then prints the updated set.

# original input set
set1 = {1, 5, 8, 12, 4, 32}

#returns deleted elements
print(set1.pop())

#prints updated set
print('Updated set after deletion:', set1)


Deleted element(s): 32
Updated set after deletion: {1, 4, 5, 8, 12}

Example: Delete if the set is empty

In this example, we are using an empty set and applying pop() function. Since the set is empty so it will generate TypeError.

# original input set
set1 = {}

#returns error
print(set1.pop())


TypeError: pop expected at least 1 argument, got 0

4. Using difference_update() function

This method uses difference_update() function of Python. It removes multiple elements from the given set. It requires a list of elements that need to be deleted. This method is useful for the programmers who want to delete a set of items in one statement.

Syntax

set.difference_update( [list] )

Parameters

list - It accepts a sequence of elements as an argument and deletes all the elements in this sequence from the set.

Example

Here, we are deleting a multiple elements at a time by using the difference_update() function.

#input set
set1 = {1, 5, 8, 12, 4, 32}

# Elements to be deleted
delete = [1, 4, 5]

# Remove all elements of list from the set
set1.difference_update(delete)

#prints updated set
print('Updated set after deletion:', set1)


Updated set after deletion: {32, 8, 12}

Conclusion

In this article, we learned to delete elements from a set by using several built-in functions such as remove(), discard(), pop() and difference_update(). We used some custom codes as well to understand different problems. We saw several examples of deletion and saw what happens if the user tries to delete an element that does not exist and what types of error generates in each situation.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.