Solve - ValueError: min() arg is an empty sequence in Python

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Check out my new book

Solve - ValueError: min() arg is an empty sequence in Python #

The Python "ValueError: min() arg is an empty sequence" occurs when we pass an empty sequence to the min() function. To solve the error, provide the default keyword argument in the call to the min() function, e.g. result = min(my_list, default=0).

valueerror min arg is an empty sequence

Here is an example of how the error occurs.

main.py
my_list = [] # ⛔️ ValueError: min() arg is an empty sequence result = min(my_list)

We passed an empty list to the min() function which caused the error.

One way to solve the error is to provide the default keyword argument in the call to the min() function.

main.py
my_list = [] result = min(my_list, default=0) print(result) # 👉️ 0

The min() function will return the value of the default keyword argument if the sequence is empty.

You can also specify a None value if a 0 doesn't suite your use case.

main.py
my_list = [] result = min(my_list, default=None) print(result) # 👉️ None

If the sequence is not empty, the smallest value will be returned.

main.py
my_list = [3, 5, 8] result = min(my_list, default=None) print(result) # 👉️ 3

You can also use a try/except block to handle the error.

main.py
my_list = [] try: result = min(my_list) except ValueError: # 👉️ handle error here result = 0 print(result) # 👉️ 0

If passing the list to the min() function causes a ValueError, the except block is ran where we can handle the error.

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

main.py
my_list = [10, 5, 20] result = min(my_list) print(result) # 👉️ 5

The function can also be passed two or more positional arguments.

main.py
result = min(10, 5, 20) print(result) # 👉️ 5

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 = min([], default=0) print(result) # 👉️ 0

If the iterable is empty and the default keyword argument is not provided, the function raises a ValueError.

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.