Post

Python Set remove() Method

In this tutorial, we will understand about the python set remove() method and its uses.

Python Set remove() Method

The Python set remove() method removes a specified element from a set. Unlike discard(), remove() raises a KeyError if the element is not found in the set.

The syntax of the remove() method is:

1
set.remove(element)

Python set remove() Parameters

The remove() method takes one parameter:

  • element: The item to be removed from the set. Must be a member of the set.

Here are examples demonstrating the remove() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Example 1: Basic remove usage
numbers = {1, 2, 3, 4}
numbers.remove(3)
print(numbers)  # Output: {1, 2, 4}

# Example 2: Removing from mixed set
mixed = {'apple', 1, (2, 3)}
mixed.remove('apple')
print(mixed)  # Output: {1, (2, 3)}

# Example 3: Handling non-existent element
fruits = {'apple', 'banana'}
try:
    fruits.remove('orange')
except KeyError:
    print("Element not found")  # Output: Element not found

The remove() method is useful when you need to ensure an element exists before removing it.

This post is licensed under CC BY 4.0 by the author.