Remove the Max and Min numbers from a List in Python

avatar

Borislav Hadzhiev

Last updated: Aug 16, 2022

banner

Photo from Unsplash

Remove the Max and Min numbers from a List in Python #

Use the list.remove() method to remove the max and min numbers from a list, e.g. my_list.remove(max(my_list)) and my_list.remove(min(my_list)). The list.remove() method will remove the max and min numbers from the original list.

main.py
my_list = [1, 25, 50, 100] # ✅ Remove max value from list my_list.remove(max(my_list)) print(my_list) # 👉️ [1, 25, 50] # ----------------------------------- # ✅ Remove min value from list my_list.remove(min(my_list)) print(my_list) # 👉️ [25, 50]

The max function returns the largest item in an iterable or the largest of two or more arguments.

main.py
my_list = [1, 25, 50, 100] result = max(my_list) print(result) # 👉️ 100

The function takes an optional default keyword argument which is used to specify a value to return if the provided iterable is empty.

main.py
result = max([], default=0) print(result) # 👉️ 0
If the iterable is empty and the default keyword argument is not provided, the function raises a ValueError.

The min function returns the smallest item in an iterable or the smallest of two or more arguments.

The list.remove() method removes the first item from the list whose value is equal to the passed in argument.

The remove() method mutates the original list and returns None.

If you want to remove the max and min numbers from a list without changing the original list, create a copy.
main.py
my_list = [1, 25, 50, 100] list_copy = my_list.copy() # ✅ Remove max value from list list_copy.remove(max(list_copy)) print(list_copy) # 👉️ [1, 25, 50] # ----------------------------------- # ✅ Remove min value from list list_copy.remove(min(list_copy)) print(list_copy) # 👉️ [25, 50]

The list.copy method returns a shallow copy of the object on which the method was called.

We created a copy, so we can remove the max and min numbers from the copy and not from the original list.

You will get a ValueError if the list you pass to the max or min function is empty.

Use a try/except statement if you need to handle the error.

main.py
my_list = [] # ✅ Remove max value from list try: my_list.remove(max(my_list)) print(my_list) # 👉️ [1, 25, 50] except ValueError: pass # ----------------------------------- # ✅ Remove min value from list try: my_list.remove(min(my_list)) print(my_list) # 👉️ [25, 50] except ValueError: pass

The max and min functions raise a ValueError when passed an empty iterable.

The list in the example is empty, so the except block runs.

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.