Python Set discard() Method (with Examples)

Python Set discard() Method: In this tutorial, we will learn about the discard() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set discard() Method

The discard() is an inbuilt method of the set class that is used to remove a given element from the set, it accepts an element and removes it from the set. If the given element does not exist in the set, the discard() method does not return any error.

Syntax

The following is the syntax of discard() method:

set_name.discard(element)

Parameter(s):

The following are the parameter(s):

  • element – It represents the element/value to be removed from the list.

Return Value

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1: Use of Set discard() Method

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# printing the sets before discard() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

# removing an element from cars_1
cars_1.discard("Porsche")
# removing an element from cars_2
cars_2.discard("Lincoln")

# printing the sets after dLincoln() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

Output

cars_1: {'Audi', 'Lexus', 'Porsche'}
cars_2: {'Mazda', 'Porsche', 'Lincoln'}
cars_1: {'Audi', 'Lexus'}
cars_2: {'Mazda', 'Porsche'}

Example 2: Use of Set discard() Method

# declaring a set
cities = {"New Delhi", "Banglore", "Indore", "Gwalior"}

# printing set before discard() call
print("cities:", cities)

# removing "New Delhi" from the set
cities.discard("New Delhi")

# removing an element that does not exist
# in the set, thus we will remove "Mumbai"
# method discard() will not give any error
cities.discard("Mumbai")

# printing set after discard() call
print("cities:", cities)

Output

cities: {'New Delhi', 'Gwalior', 'Indore', 'Banglore'}
cities: {'Gwalior', 'Indore', 'Banglore'}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.