Remove elements from Set – Python

Sets are mutable collection datatype in Python. So we can perform add (append), update (change), delete (remove) operations on the set objects.

In article Add elements in Set, we learned about methods to add single element and multiple elements in Set collection. In this article, we will learn about various methods to remove (delete) elements from Set.

Remove element from Set

In Python, Set has multiple built-in methods to remove (delete) elements from it. We can use remove(), discard(), pop() and clear() methods to take out elements from Set.

  • set.remove(element) method removes the given element from set. Before using remove() we should ensure that element exists in the Set. remove() method throws error if element does not exists into the set.
  • set.discard(element) method also removes the given element from set. discard() method does not throws error if element not exists into the set.
  • remove() and discard() methods just remove the element from the Set and does not return any value.
  • set.pop() method is used to take out element from the set. pop() method returns the element taken out (removed) from the Set. Because Set is an unordered collection, any element can be removed from Set.
  • set.clear() method is used to remove all elements from the Set. clear() method does not return any value.

Lets see programs to remove elements from Set using remove(), discard(), pop() and clear() methods.

Remove element from Set – using remove() method

In this case we will use remove() method to remove the element from Set. set.remove(element) method removes the given element from set. Before using remove() we should ensure that element exists in the Set. remove() method throws error if element does not exists into the set. remove() method does not return any value.

# remove element from set - using remove() method
print("remove element from set - using remove() method")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}
print(numbers_set)

number = numbers_set.remove(40)           # remove element 40 from set using remove() method

print(numbers_set)         # print set elements after removing element
print(number)                  # print returned number value

We have defined a Set of number elements. we are using built-in remove() method on Set, to remove element 40 from this Set. 40 exists as an element of the Set. Although remove() method does not return any value but to verify we are taking the return value in variable ‘number’. After removal, we are printing the Set elements and the return ‘number’.

Program Output

remove element from set - using remove() method
{70, 40, 10, 80, 50, 20, 90, 60, 30}
{70, 10, 80, 50, 20, 90, 60, 30}                    # element 40 removed from the Set
None                    # No value was returned from remove() method

From the program output, element 40 was removed from the Set using remove() method and None was returned.

Error – remove() method – element not exists in Set

In this case we will use remove() method to remove the element from Set. Before using remove() we should ensure that element exists in the Set. remove() method throws error if element does not exists into the set.

# remove element from set - raise error if element does not exists
print("remove element from set - raise error if element does not exists")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}      # element 100 does not exists in Set
print(numbers_set)

numbers_set.remove(100)      # remove element 100 from set using remove() method

We have defined a Set of number elements. we are using built-in remove() method on Set, to remove element 100 from this Set. Element 100 does not exists in the Set. remove() method will throw KeyError.

Program Output

remove element from set - raise error if element does not exists
{70, 40, 10, 80, 50, 20, 90, 60, 30}
Traceback (most recent call last):
  File "D:\remove-element-set.py", line 16, in <module>
    numbers_set.remove(100)
KeyError: 100

From the program output, element 100 does not exists in the Set and remove() method throws KeyError for the element.

Using discard() method

In this case we will use discard() method to remove the element from Set. set.discard(element) method removes the given element from set. discard() method does not throws error if element does not exists into the set. discard() method does not return any value.

# remove element from set - using discard() method
print("remove element from set - using discard() method")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}
print(numbers_set)

number = numbers_set.discard(40)          # remove element 40 from set using discard() method

print(numbers_set)           # print set elements after removing element
print(number)                    # print returned number value

In this program, we have defined a Set of number elements referenced by a variable ‘number_set’. we are using built-in discard() method on Set, to remove element 40 from this Set. 40 exists as an element of the Set. Although discard() method does not return any value but to verify we are taking return value in variable ‘number’. After removal, we are printing the Set elements and the return ‘number’.

Program Output

remove element from set - using discard() method
{70, 40, 10, 80, 50, 20, 90, 60, 30}
{70, 10, 80, 50, 20, 90, 60, 30}                    # element 40 removed from the Set
None            # No value was returned from discard() method

From the program output, element 40 was removed from the Set using discard() method and None was returned.

discard() method no error thrown – element not exists in Set

In this case we will use discard() method to remove the element from Set. discard() method does not throws error if element does not exists into the set.

# discard() method does not raise error if element does not exists
print("discard() method does not raise error if element does not exists")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}      # element 100 does not exists in Set
print(numbers_set)

number = numbers_set.discard(100)           # remove element 100 from set using discard() method

print(numbers_set)
print(number)

We have defined a Set of number elements. we are using built-in discard() method on Set, to remove element 100 from this Set. Element 100 does not exists in the Set. discard() method will neither remove any element nor it will throw any error.

Program Output

discard() method does not raise error if element does not exists
{70, 40, 10, 80, 50, 20, 90, 60, 30}
{70, 40, 10, 80, 50, 20, 90, 60, 30}          # no change in elements of Set
None           # No value was returned from discard() method

From the program output, element 100 does not exists in the Set and discard() method neither remove any element nor it will throw any error. None returned.

Using pop() method

In this case we will use pop() method to take out the element from Set. Set is an unordered collection, so set.pop() method removes any element from Set. pop() method return element.

# pop() method to take out an element - order is not defined
print("pop() method to take out an element - order is not defined")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}
print(numbers_set)

number = numbers_set.pop()           # take out any element from set using pop() method

print(numbers_set)          # print set elements after pop element
print(number)          # print returned number value

In this program, we have defined a Set of number elements referenced by a variable ‘number_set’. we are using built-in pop() method on Set, to take out any element from this Set. pop() method returns element which is taken out.

Program Output

pop() method to take out an element - order is not defined
{70, 40, 10, 80, 50, 20, 90, 60, 30}
{40, 10, 80, 50, 20, 90, 60, 30}             # any element taken out from the Set
70          # Take out element was returned from pop() method

From the program output, any element was removed from the Set using pop() method and take out element was returned.

Using clear() method

In this case we will use clear() method to remove all elements from Set. clear() method removes all elements from Set. clear() method does not return any value.

# clear() method to remove all elements from set
print("clear() method to remove all elements from set")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}
print(numbers_set)

number = numbers_set.clear()       # remove all elements from set using clear() method

print(numbers_set)         # print empty set after removing all elements
print(number)          # print returned number value

W have defined a Set of number elements. we are using built-in clear() method on Set to remove all elements from this Set. clear() method does not return any value.

Program Output

clear() method to remove all elements from set
{70, 40, 10, 80, 50, 20, 90, 60, 30}
set()            # empty set after removing all elements
None        # No value was returned from clear() method

From the program output, all elements were removed from the Set using clear() method and None returned.

Delete Set – Using del

In this case we will use del command to delete the Set itself. Once the Set is deleted, it cannot be accessed. We will get an error, if we try to access deleted Set or try to perform any operation on deleted Set.

# del will delete the set itself
print("del will delete the set itself")

numbers_set = {10, 20, 30, 40, 50, 60, 70, 80, 90}
print(numbers_set)

del numbers_set            # using del, to delete the Set
print(numbers_set)       # Throws error, after delete Set does not exists

W have defined a Set of number elements. we are using del command to delete Set. After deletion, we are printing the elements of the Set, which will throw an error.

Program Output

del will delete the set itself
{70, 40, 10, 80, 50, 20, 90, 60, 30}
Traceback (most recent call last):
  File "D:\remove-element-set.py", line 70, in <module>
    print(numbers_set)
          ^^^^^^^^^^^
NameError: name 'numbers_set' is not defined

From the program output, Set ‘number_set’ was deleted. After deletion, when we tried to print Set elements, we got an error NameError: name 'numbers_set' is not defined.

Summary

In this article we learn about various methods to remove elements from the Set. Following scenarios were explored:

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Q: How can we remove multiple elements from a set at once?

We can use multiple ways to remove multiple elements from a set.

  • We can iterate over the elements and use either remove() or discard() method to remove elements from the set.
numbers_set = {12, 22, 33, 46, 58}
elements_to_remove = {22, 33}
for element in elements_to_remove:
	numbers_set.discard(element)  # or we can use numbers_set.remove(element)
print(numbers_set)   # Elements remain in numbers_set {58, 12, 46}
  • We can also use set operations like difference or difference_update.
numbers_set = {12, 22, 33, 46, 58}
elements_to_remove = {22, 33}
difference_set = numbers_set - elements_to_remove
print(difference_set)   # Elements remain in difference_set {58, 12, 46}

numbers_set = {12, 22, 33, 46, 58}
elements_to_remove = {22, 33}
numbers_set.difference_update(elements_to_remove)
print(numbers_set)   # Elements remain in numbers_set {58, 12, 46}

Q: What will happen if we use the pop() method on an empty set?

If we will use the pop() method on an empty set, it will raise a KeyError because there are no elements to remove in the set.

empty_set = set()    # an empty set
try:
    empty_set.pop()  # This will raise a KeyError
except KeyError as error:
    print("KeyError raised - ", error)    # KeyError raised -  'pop from an empty set'

Q: How would remove an element from a set, which may or may not exists in the set?

In this case, it’s safe to use discard() method because it does not raise an error if the element is not present in the set. e.g. set.discard(4) # No error thrown even if element 4 does not present in the set

remove() method will raise an error if element is not present in the set.

set = {14, 24, 34}
if 4 in set:
    set.remove(4)  # Will only remove if 4 exists

Q: Explain the time complexity of removing an element from the set?

Time complexity of removing an element from a set is on average O(1) and it is same for methods remove(), discard(), or pop(). Sets in Python are implemented as hash tables, where operations like insertion, deletion, and lookup can be performed in constant time.

In the worst-case scenario, of multiple hash collisions the time complexity can degrade to O(n), where n is the number of elements in the set. But such cases are rare and Python’s hash function is designed to minimize collisions.

Q: Is it possible to remove elements from a frozen set?

No, it is not possible to remove elements from a frozen set. A frozen set is an immutable version of a set, meaning once it is created, it cannot be modified. This immutability ensures that the set’s elements cannot be changed, added, or removed.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *