AppDividend
Latest Code Tutorials

# Python Set discard() Method Example

Python Set discard() is an inbuilt function that removes any specified element from a set. The discard() method only removes an item that is present in the Set. The set discard() method is different from the set remove() method because the remove() method will raise the error if the specified item does not exist, whereas the discard() method will not raise any error.

Python inbuilt set method discard() removes an item from the set only if the item is present in the set. If the item is not present in the set, then no error or exception is raised, and the original set is returned.

#### Syntax

`set.discard(element)`

It takes one argument called an element, which we want to remove from the set.

#### Return Value

The discard() method does not return any value; it just returns None.

See the following code example.

```# app.py

# creating a set of even numbers till 10
evens = {2, 4, 6, 8, 10}
# Printing the set
print("The set is: ", evens)

# Now we will discard 8 from the set

# Printing new set
print("New set is: ", evens)

# Asking user to enter the value
x = int(input("Enter number which you want to discard: "))
# printing the new set
print("Now new set is: ", evens)
```

#### Output

```The set is:  {2, 4, 6, 8, 10}
New set is:  {2, 4, 6, 10}
Enter number which you want to discard: 4
Now new set is:  {2, 6, 10}
```

In this example, we have created a set of even numbers until 10. Then we have discarded 8 from the set and see what the result is.

Then we have asked the user to give input on which number he/she wants to discard, and then we have called discard() function and removed that element.

Please note that if the user enters any number which is not present in the set, then it will do nothing.

## Element is not present in Set

Let’s take a scenario in which the item is not present in the set, and we try to remove the item from the set using discard() method.

```# app.py

def RemoveElement(setA):
print(setA)

setA = set([11, 21, 19, 46, 29, 18])
RemoveElement(setA)
```

#### Output

```python3 app.py
{11, 46, 18, 19, 21, 29}```

From the output, it returns the original set and does not raise any exception. The order of the element is different, but the items are the same.

Finally, Python Set discard() Method Example is over.