This question involves two tasks.
Here,
min()
and max()
function to find out the smallest and greatest element in the list.remove()
method which deletes/removes the given element from the set.Syntax for remove() set method
<set_object>.remove(<element_to_be_removed>)
Example
samp_set = {7, 4, 5, 3, 8}
samp_set.remove(5)
print("Set after removing element: ")
print(samp_set)
Output
Set after removing element: {3, 4, 7, 8}
Some Important Points to Remember About set remove() method:
remove()
method does not return anything. Basically, it returns None (None Type in Python).KeyError
.There is also remove() method to delete the element from the list.
Now we will use the above remove() method.
Python Program
samp_set = {7, 4, 5, 3, 8}
print("Origional set: ")
print(samp_set)
samp_set.remove(min(samp_set))
print("Set after removing smallest element: ")
print(samp_set)
print("Set after removing greatest element: ")
samp_set.remove(max(samp_set))
print(samp_set)
Output
Origional set: {3, 4, 5, 7, 8} Set after removing smallest element: {4, 5, 7, 8} Set after removing greatest element: {4, 5, 7}
If you keep removing elements, the set will become empty. When you try to remove an element from an empty set, it will throw an error. To avoid this, you can put the if-statement to verify whether the set is empty or not.
samp_set = set()
if samp_set:
samp_set.remove(min(samp_set))
print("Set after removing element: ")
print(samp_set)
Output
Set after removing element: set()
Basically if the set is empty and if you try to remove the element from it, it remains empty.
Set can also be used to check if all the elements in the list are same.
This is a simple tutorial where we have learned to remove the smallest and greatest element from the Python set