×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Set discard() Method (with Examples)

Last Updated : December 11, 2025

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'}
Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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