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

avatar

Borislav Hadzhiev

Sun Apr 24 20222 min read

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

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

valueerror max arg is an empty sequence

Here is an example of how the error occurs.

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

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

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

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

The max() 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 = max(my_list, default=None) print(result) # 👉️ None

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

main.py
my_list = [10, 30, 20] result = max(my_list, default=None) print(result) # 👉️ 30

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

main.py
my_list = [] try: result = max(my_list) except ValueError: result = 0 print(result) # 👉️ 0

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

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

main.py
my_list = [15, 45, 30] result = max(my_list) print(result) # 👉️ 45

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

main.py
result = max(15, 45, 30) print(result) # 👉️ 45

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.