How to Solve Python ValueError: max() arg is an empty sequence

by | Programming, Python, Tips

The max() function is built into Python and returns the item with the highest value in an iterable or the item with the highest value from two or more objects of the same type. When you pass an iterable to the max() function, such as a list, it must have at least one value to work. If you use the max() function on an empty list, you will raise the error “ValueError: max() arg is an empty sequence”.

To solve this error, ensure you only pass iterables to the max() function with at least one value. You can check if an iterable has more than one item by using an if-statement, for example,

if len(iterable) > 0: 
    max_value = max(iterable)

This tutorial will go through the error in detail and how to solve it with a code example.


ValueError: max() arg is an empty sequence

What is a Value Error in Python?

In Python, a value is a piece of information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value. Let’s look at an example of a ValueError:

value = 'string'

print(float(value))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
print(float(value))

ValueError: could not convert string to float: 'string'

The above code throws the ValueError because the value ‘string‘ is an inappropriate (non-convertible) string. You can only convert numerical strings using the float() method, for example:

value = '5'
print(float(value))
5.0

The code does not throw an error because the float function can convert a numerical string. The value of 5 is appropriate for the float function.

The error ValueError: max() arg is an empty sequence is a ValueError because while an iterable is a valid type of object to pass to the max() function, the value it contains is not valid.

Using max() in Python

The max() function returns the largest item in an iterable or the largest of two or more arguments. Let’s look at an example of the max() function to find the maximum of three integers:

var_1 = 3
var_2 = 5
var_3 = 2

max_val = max(var_1, var_2, var_2)

print(max_val)

The arguments of the max() function are the three integer variable. Let’s run the code to get the result:

5

Let’s look at an example of passing an iterable to the max() function. In this case, we will use a string. The max() function finds the maximum alphabetical character in a string.

string = "research"

max_val = max(string)

print(max_val)

Let’s run the code to get the result:

s

When you pass an iterable the max() function, it must contain at least one value. The max() function cannot return the largest item if no items are present in the list. The same applies to the min() function, which finds the smallest item in a list.

Example: Returning a Maximum Value from a List using max() in Python

Let’s write a program that finds the maximum number of bottles sold for different drinks across a week. First, we will define a list of drinks:

drinks = [

{"name":"Coca-Cola", "bottles_sold":[10, 4, 20, 50, 29, 100, 70]},

{"name":"Fanta", "bottles_sold":[20, 5, 10, 50, 90, 10, 50]},

{"name":"Sprite", "bottles_sold":[33, 10, 8, 7, 34, 50, 21]},

{"name":"Dr Pepper", "bottles_sold":[]}

]

The list contains four dictionaries. Each dictionary contains the name of a drink and a list of the bottles sold over seven days. The drink Dr Pepper recently arrived, meaning no bottles were sold. Next, we will iterate over the list using a for loop and find the largest amount of bottles sold for each drink over seven days.

for d in drinks:

    most_bottles_sold = max(d["bottles_sold"])

    print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold))

We use the max() function in the above code to get the largest item in the bottles_sold list. Let’s run the code to get the result:

The largest amount of Coca-Cola bottles sold this week is 100.
The largest amount of Fanta bottles sold this week is 90.
The largest amount of Sprite bottles sold this week is 50.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 for d in drinks:
      2     most_bottles_sold = max(d["bottles_sold"])
      3     print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold))
      4 

ValueError: max() arg is an empty sequence

The program raises the ValueError because Dr Pepper has an empty list.

Solution

To solve this error, we can add an if statement to check if any bottles were sold in a week before using the max() function. Let’s look at the revised code:

for d in drinks:

    if len(d["bottles_sold"]) > 0:

        most_bottles_sold = max(d["bottles_sold"])

        print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold)

    else:

        print("No {} bottles were sold this week.".format(d["name"]))

The program will only calculate the maximum amount of bottles sold for a drink if it was sold for at least one day. Otherwise, the program will inform us that the drink was not sold for that week. Let’s run the code to get the result:

The largest amount of Coca-Cola bottles sold this week is 100.
The largest amount of Fanta bottles sold this week is 90.
The largest amount of Sprite bottles sold this week is 50.
No Dr Pepper bottles were sold this week.

The program successfully prints the maximum amount of bottles sold for Coca-Cola, Fanta, and Sprite. The bottles_sold list for Dr Pepper is empty; therefore, the program informs us that no Dr Pepper bottles were sold this week.

Summary

Congratulations on reading to the end of this tutorial! The error: “ValueError: max() arg is an empty sequence” occurs when you pass an empty list as an argument to the max() function. The max() function cannot find the largest item in an iterable if there are no items. To solve this, ensure your list has items or include an if statement in your program to check if a list is empty before calling the max() function.

For further reading of ValueError, go to the articles:

For further reading on using the max() function, go to the article:

How to Find the Index of the Max Value in a List in Python

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee