How to Remove The Smallest Element from the Set Python?

How to Remove The Smallest Element from the Set Python?

This question involves two tasks.

  • Find the smallest (or greatest) element from the set.
  • Remove/delete them from the set

Here,

  • We are using min() and max() function to find out the smallest and greatest element in the list.
  • Set has a remove() method which deletes/removes the given element from the set.

How to Remove Element from Python 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:

  • This remove() method does not return anything. Basically, it returns None (None Type in Python).
  • When you try to remove the element which is not present in the set, it actually throws a KeyError.

There is also remove() method to delete the element from the list.

How to Remove The Smallest and Greatest Element from the Python Set?

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

Leave a Reply

Your email address will not be published. Required fields are marked *