Post

Python Set discard() Method

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

Python Set discard() Method

The Python set discard() method removes a specified element from a set if it exists. Unlike remove(), discard() doesn’t raise a KeyError if the element is not found in the set. This makes it safer when you’re not sure if an element exists.

The syntax of the discard() method is:

1
set.discard(element)

Python set discard() Parameters

The discard() method takes one parameter:

  • element: The item to be removed from the set. Can be of any type that’s hashable.

Here are examples demonstrating the discard() method:

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

# Example 2: Discarding non-existent element
fruits = {'apple', 'banana', 'orange'}
fruits.discard('grape')  # No error raised
print(fruits)  # Output: {'apple', 'banana', 'orange'}

# Example 3: Discarding different types
mixed_set = {1, 'hello', (1, 2)}
mixed_set.discard((1, 2))
print(mixed_set)  # Output: {1, 'hello'}

The discard() method is particularly useful in situations where you want to remove elements without checking their existence first.

Khushal Jethava
Khushal Jethava

Machine Learning Engineer at Codiste, specializing in Generative AI, NLP, and Computer Vision. Building production AI systems with Python.

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