C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Set discard() MethodPython discard() method discards or remove the elememt from the set. This method does not return anything, even no error if the elememt is not present. It takes a parameter which is an elememt to be removed. The method signature is given below. Signature
discard(elem) Parameters
elem: element to be deleted. ReturnIt returns None. Let's see some examples of discard() method to understand it's functionality. Python Set discard() Method Example 1
A simple example to use discard method to remove an element.
# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set)
# Calling function
set.discard(2)
print(set)
Output: {1, 2, 3, 4, 5}
{1, 3, 4, 5}
Python Set discard() Method Example 2If the element is not present it returns none to the caller method.
# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set)
# Calling function
val = set.discard(22)
print(val)
Output: {1, 2, 3, 4, 5}
None
Python Set discard() Method Example 3An example where we are implementing this method into a program. It removes all odds elements.
# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
set2 = {1,2,3,4,5}
# Displaying elements
print(set)
# Calling function
for s in set2:
if s%2!=0:
set.discard(s) # Discard all odd elements
print(set)
Output: {1, 2, 3, 4, 5}
{2, 4}
Next TopicPython Set
|