Python Set discard()

The discard() method removes a specified element from the set (if present).

The syntax of discard() in Python is:

s.discard(x)

discard() Parameters

The discard() method takes a single element x and removes it from the set (if present).


Return Value from discard()

The discard() removes element x from the set if the element is present.

This method returns None (meaning, absence of a return value).


Example 1: How discard() works?

numbers = {2, 3, 4, 5}

numbers.discard(3)
print('numbers = ', numbers)

numbers.discard(10)
print('numbers = ', numbers)

When you run the program, the output will be:

numbers =  {2, 4, 5}
numbers =  {2, 4, 5}

Example 2: How discard() works?

numbers = {2, 3, 5, 4}

# Returns None
# Meaning, absence of a return value 
print(numbers.discard(3))

print('numbers =', numbers)

When you run the program, the output will be:

None
numbers = {2, 4, 5}