valueerror: max()/min() arg is an empty sequence Python – Code Example

Total
0
Shares

Python throws valueerror: max() arg is an empty sequence when argument of max() function is an empty iterable like list. Similarly min() function throws the error. According to Python documentation

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

The max() function can accept either an iterable or multiple values as arguments. This valueerror of empty sequence is raised when we provide iterable agument.

Code Example

Error Code – Let’s first reproduce the error –

lst = []
print(max(lst))

Since the list is empty, it will throw the error –

Traceback (most recent call last):
  File "/home/jdoodle.py", line 2, in <module>
    print(max(lst))
ValueError: max() arg is an empty sequence

Solutions

1. Using default as argument

We can use default as second argument to max() or min() function. It will substitute the value of default is list is empty.

lst = []
print(max(lst, default=0))

Output –

0

2. Check length of list using if condition

Before fetching the maximum value using max(), you can check the length of list first –

lst = []
if lst:
    print(max(lst))
else:
    print("list is empty")

Output –

list is empty

3. Using inline if-else

lst = []
print(max(lst) if lst else "Empty List")

Output –

Empty List

4. Using Or

lst = []
print(max(lst or [0]))

Using or will replace the empty list with another list you provide. In this example I provided [0] so it will take it to find max. Output –

0

Here I am providing a code to get the longest word in the string using max() function –

def longest_word(text):
    z = []
    x = text.split(' ')
    for i in x:
        z.append(len(i))
    f = z.index(max(z))
    return x[f]
    
print(longest_word("Even dead I'm The Hero - EDITH"))

Output –

EDITH

Live Demo

Open Live Demo