Borislav Hadzhiev
Last updated: Apr 24, 2022
Check out my new book
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)
.
Here is an example of how the error occurs.
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.
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.
my_list = [] result = min(my_list, default=None) print(result) # 👉️ None
If the sequence is not empty, the smallest value will be returned.
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.
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.
my_list = [10, 5, 20] result = min(my_list) print(result) # 👉️ 5
The function can also be passed two or more positional arguments.
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.
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
.