Click for All Topics
keyError.
Syntax –
set_name.remove(element)
Parameter –
Example 1 – let’s see an example
my_set={1,2,3,4,5}
print(my_set)
my_set.remove(5)
print(my_set)
# Output -
# {1,2,3,4,5} # my_set before removing element from set
# {1,2,3,4} # my_set after removing element(5) from set
Example 2- trying to remove an element that do not exist
set1={'e','d','S','l','a','s','h'}
print(set1)
set1.remove('o') # will raise an error
# Output -
# {'e','d','S','l','a','s','h'}
# Traceback (most recent call last):
# File "/home/main.py", line 3, in
# set1.remove('o')
# KeyError: 'o'
Example 3- trying to give two arguments let’s see
s={14,8,19,25,29,11}
print(s)
s.remove(8,19) # will raise an error
# Output -
# {14,8,19,25,29,11}
# Traceback (most recent call last):
# File "/home/main.py", line 3, in
# s.remove(8,19)
# TypeError: set.remove() takes exactly one argument (2 given)
if you have to remove multiple elements from the set then you have to call the remove method multiple times.
Let’s see the example –
s={11,22,33,44,55,66,77,88,99}
print(s)
s.remove(11)
print(s)
s.remove(44)
print(s)
# Output -
# {11,22,33,44,55,66,77,88,99} # before removing the element from the set
# {22,33,44,55,66,77,88,99} # set after removing 11
# {22,33,55,66,77,88,99} # set after removing 44
Example 4-
s={'hello','everyone','this','is','edSlash'}
print(s)
return_value=s.remove('hello')
print(s)
print(return_value)
# Output -
# {'hello','everyone','this','is','edSlash'} # original set
# {'everyone','this','is','edSlash'} # modified set
# None # return value of remove method
Example 5- Removing odd element from the set
s={1,2,3,4,5,6,7,8,9}
s1=s.copy()
print("original set",s)
print("copied set:",s1)
for i in s1:
if i%2==1:
s.remove(i)
print(s)
# Output -
# original set: {1, 2, 3, 4, 5, 6, 7, 8, 9}
# copied set: {1, 2, 3, 4, 5, 6, 7, 8, 9}
# modified original set: {2, 4, 6, 8}
remove() | discard() |
It will raise an error if an element is not present in the set | It will not give an error whether an element is present in the set or not |
It is beneficial when you know the element of the set | It is ideal when you have no idea about the element of the set |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India