.remove()

Published May 18, 2024
Contribute to Docs

In Python, the .remove() method removes a specified element from a set. If the element is not found, it raises a KeyError.

Syntax

set.remove(element)
  • set: The set from which the element is to be removed.
  • element: The element to be removed from the set.

Example

The below example shows the usage of the .remove() method:

# Creating a set
my_set = {1, 2, 3, 4, 5}
# Removing '4' from the set
my_set.remove(4)
# Printing the modified set
print(my_set)
# Removing '6' from the set
my_set.remove(6)
# Printing the modified set
print(my_set)

The above code produces the following output:

{1, 2, 3, 5}
KeyError: 6

In the above example, the .remove() method raises a KeyError since the element 6 doesn’t exist in my_set.

Codebyte Example

Below is a codebyte example demonstrating the use of the .remove() method:

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy