# Set discard() remove() and pop() in Python HackerRank Solution

#### ByBrokenprogrammers

Dec 9, 2022

Hello Programmers, In this post, you will know how to solve the Set discard() remove() and pop() in Python HackerRank Solution. This problem is a part of the HackerRank Python Programming Series.

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

## Set discard() remove() and pop() in Python HackerRank Solution

### problem

.remove(x)
This operation removes element x from the set.
If element x does not exist, it raises a KeyError.
The .remove(x) operation returns None.
Example :

```>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0
```

This operation also removes element x from the set.
If element x does not exist, it does not raise a KeyError.
Example :

```>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
```

.pop()
This operation removes and return an arbitrary element from the set.
If there are no elements to remove, it raises a KeyError.
Example :

```>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set
```

You have a non-empty set s, and you have to execute N commands given in N lines.
The commands will be pop, remove and discard.

#### Input Format :

The first line contains integer n, the number of elements in the set s.
The second line contains n space separated elements of set s. All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer N, the number of commands.
The next N lines contains either pop, remove and/or discard commands followed by their associated value.

• 0 < n < 20
• 0 < N < 20

#### Output Format :

Print the sum of the elements of set s on a single line.

### Set discard() remove() and pop() in Python HackerRank Solutions

```# Set discard() remove() and pop() in Python - Hacker Rank Solution
# Python 3
# Set discard() remove() and pop() in Python - Hacker Rank Solution START
n = int(input())
s = set(map(int,input().split()))
num = int(input())
for i in range(num):
ip = input().split()
if ip[0]=="remove":
s.remove(int(ip[1]))
else :
s.pop()
print(sum(list(s)))
# Set discard() remove() and pop() in Python - Hacker Rank Solution END```

Disclaimer: The above Problem (Set discard() remove() and pop() in Python) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.