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.
Table of contents
- ValueError: max() arg is an empty sequence
- What is a Value Error in Python?
- Using max() in Python
- Example: Returning a Maximum Value from a List using max() in Python
- Solution
- Summary
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:
- How to Solve Python ValueError: cannot convert float nan to integer
- How to Solve Python ValueError: if using all scalar values, you must pass an index
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!
The max() method only works if you pass a sequence with at least one value into the method.
If you try to find the largest item in an empty list, you’ll encounter the error “ValueError: max()
arg is an empty sequence”.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you figure out how to resolve this error.
ValueError: max() arg is an empty sequence
The max()
method lets you find the largest item in a list. It is similar to the min()
method which finds the smallest item in a list.
For this method to work, max()
needs a sequence with at least one value. This is because you cannot find the largest item in a list if there are no items. The largest item is non-existent because there are no items to search through.
A variation of the “ValueError: max()
arg is an empty sequence” error is found when you try to pass an empty list into the min()
method. This error is “ValueError: min()
arg is an empty sequence”. This min()
error occurs for the same reason: you cannot find the smallest value in a list with no values.
An Example Scenario
We’re going to build a program that finds the highest grade a student has earned in all their chemistry tests. To start, define a list of students:
students = [ { "name": "Ron", "grades": [75, 92, 84] }, { "name": "Katy", "grades": [92, 86, 81] }, { "name": "Rachel", "grades": [64, 72, 72] }, { "name": "Miranda", "grades": [] } ]
Our list of students contains four dictionaries. These dictionaries contain the names of each student as well as a list of the grades they have earned. Miranda does not have any grades yet because she has just joined the chemistry class.
Next, use a for loop to go through each student in our list of students and find the highest grade each student has earned and the average grade of each student:
for s in students: highest_grade = max(s["grades"]) average_grade = round(sum(s["grades"]) / len(s["grades"])) print("The highest grade {} has earned is {}. Their average grade is {}.".format(s["name"], highest_grade, average_grade))
We use the max()
function to find the highest grade a student has earned. To calculate a student’s average grade, we divide the total of all their grades by the number of grades they have received.
We round each student’s average grade to the nearest whole number using the round()
method.
Run our code and see what happens:
The highest grade Ron has earned is 92. Their average grade is 84. The highest grade Katy has earned is 92. Their average grade is 86. The highest grade Rachel has earned is 72. Their average grade is 69. Traceback (most recent call last): File "main.py", line 10, in <module> highest_grade = max(s["grades"]) ValueError: max() arg is an empty sequence
Our code runs successfully until it reaches the fourth item in our list. We can see Ron, Katy, and Rachel’s highest and average grades. We cannot see any values for Miranda.
The Solution
Our code works on the first three students because each of those students have a list of grades with at least one grade. Miranda does not have any grades yet.
Because Miranda does not have any grades, the max()
function fails to execute. max()
cannot find the largest value in an empty list.
To solve this error, see if each list of grades contains any values before we try to calculate the highest grade in a list. If a list contains no values, we should show a different message to the user.
Let’s use an “if” statement to check if a student has any grades before we perform any calculations:
for s in students: if len(s["grades"]) > 0: highest_grade = max(s["grades"]) average_grade = round(sum(s["grades"]) / len(s["grades"])) print("The highest grade {} has earned is {}. Their average grade is {}.".format(s["name"], highest_grade, average_grade)) else: print("{} has not earned any grades.".format(s["name"]))
Our code above will only calculate a student’s highest and average grade if they have earned at least one grade. Otherwise, the user will be informed that the student has not earned any grades. Let’s run our code:
The highest grade Ron has earned is 92. Their average grade is 84. The highest grade Katy has earned is 92. Their average grade is 86. The highest grade Rachel has earned is 72. Their average grade is 69. Miranda has not earned any grades.
Our code successfully calculates the highest and average grades for our first three students. When our code reaches Miranda, our code does not calculate her highest and average grades. Instead, our code informs us that Miranda has not earned any grades yet.
Conclusion
The “ValueError: max()
arg is an empty sequence” error is raised when you try to find the largest item in an empty list using the max()
method.
To solve this error, make sure you only pass lists with at least one value through a max()
statement. Now you have the knowledge you need to fix this problem like a professional coder!
Thread Rating:
- 0 Vote(s) — 0 Average
- 1
- 2
- 3
- 4
- 5
error: max() arg is an empty sequence |
Oct-10-2016, 08:00 PM Hello everyone, I’m trying to compile this code: for idx, i in enumerate(array): if idx > phaseshift: if abs(i - array[idx - phaseshift]) > 1000 or True: self.phasespace_x.append(array[idx - phaseshift]) self.phasespace_y.append(i + array[idx - phaseshift]) self.linx = [max(self.phasespace_x),min(self.phasespace_x)] where the problem was at first in array variable. It was not defined. To reduce the error in the «enumerate » line I defined array as empty list as: array=[]. Because when I defined array as integer I got an error that integer in enumerate cannot be interated . Now I have this:
which is quite logic I think because of empty variable array. Could you please tell me how to fix this problem? Thank you. Posts: 2,144 Threads: 35 Joined: Sep 2016 Reputation: You could give a default value that’s returned by max If the iterable is empty. values = [] print(max(values, default=0))
Posts: 9 Threads: 3 Joined: Oct 2016 Reputation:
Thank you. Problem removed. |
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
TypeError: sequence item 0: expected str instance, float found Error Query | eddywinch82 | 1 | 3,203 |
Sep-04-2021, 09:16 PM Last Post: eddywinch82 |
|
Error : «can’t multiply sequence by non-int of type ‘float’ « | Ala | 3 | 2,291 |
Apr-13-2021, 10:33 AM Last Post: deanhystad |
|
Empty response to request causing .json() to error | t4keheart | 1 | 5,770 |
Jun-26-2020, 08:35 PM Last Post: bowlofred |
|
empty json file error | mcmxl22 | 1 | 6,893 |
Jun-17-2020, 10:20 AM Last Post: buran |
|
PyODBC error — second parameter to executemany must be a sequence, iterator, or gener | RBeck22 | 1 | 5,712 |
Mar-29-2019, 06:44 PM Last Post: RBeck22 |
|
ValueError — arg is an empty sequence | jojotte | 2 | 4,588 |
Dec-31-2018, 10:07 AM Last Post: jojotte |
Вопрос:
Оценка,
max_val = max(a)
приведет к ошибке,
ValueError: max() arg is an empty sequence
Существует ли лучший способ защиты от этой ошибки, отличной от try
, except
catch?
a = []
try:
max_val = max(a)
except ValueError:
max_val = default
Лучший ответ:
В Python 3.4+ вы можете использовать default
аргумент ключевого слова:
>>> max([], default=99)
99
В более низкой версии вы можете использовать or
:
>>> max([] or [99])
99
ПРИМЕЧАНИЕ. Второй подход не работает для всех итераций. особенно для итератора, которые не дают ничего, кроме значения истины.
>>> max(iter([]) or 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
Ответ №1
В версиях Python старше 3.4 вы можете использовать itertools.chain()
, чтобы добавить другое значение в возможную пустую последовательность. Это будет обрабатывать любые пустые итерации, но обратите внимание, что это не то же самое, что и поставлять аргумент default
, поскольку добавочное значение всегда включено:
>>> from itertools import chain
>>> max(chain([42], []))
42
Но в Python 3.4 по умолчанию игнорируется, если последовательность не пуста:
>>> max([3], default=42)
3
Ответ №2
Другим решением может быть использование троичных операторов:
nums = []
max_val = max(nums) if nums else 0
или
max val = max(iter(nums) if nums else [0])
Ответ №3
_DEFAULT = object()
def max_default(*args, **kwargs):
"""
Adds support for "default" keyword argument when iterable is empty.
Works for any iterable, any default value, and any Python version (versions >= 3.4
support "default" parameter natively).
Default keyword used only when iterable is empty:
>>> max_default([], default=42)
42
>>> max_default([3], default=42)
3
All original functionality is preserved:
>>> max_default([])
Traceback (most recent call last):
ValueError: max() arg is an empty sequence
>>> max_default(3, 42)
42
"""
default = kwargs.pop('default', _DEFAULT)
try:
return max(*args, **kwargs)
except ValueError:
if default is _DEFAULT:
raise
return default
Бонус:
def min_default(*args, **kwargs):
"""
Adds support for "default" keyword argument when iterable is empty.
Works for any iterable, any default value, and any Python version (versions >= 3.4
support "default" parameter natively).
Default keyword used only when iterable is empty:
>>> min_default([], default=42)
42
>>> min_default([3], default=42)
3
All original functionality is preserved:
>>> min_default([])
Traceback (most recent call last):
ValueError: min() arg is an empty sequence
>>> min_default(3, 42)
3
"""
default = kwargs.pop('default', _DEFAULT)
try:
return min(*args, **kwargs)
except ValueError:
if default is _DEFAULT:
raise
return default
Ответ №4
Максимум пустой последовательности “должен” быть бесконечно малой величиной любого типа, который имеют элементы последовательности. К сожалению, (1) с пустой последовательностью вы не можете определить, какой тип должны были иметь элементы, и (2) есть, например, не такая вещь, как наибольшее отрицательное целое в Python.
Итак, вам нужно помочь max
, если вы хотите, чтобы в этом случае было что-то разумное. В последних версиях Python есть аргумент default
для max
(который мне кажется вводящим в заблуждение именем, но неважно), который будет использоваться, если вы пройдете в пустой последовательности. В более старых версиях вам просто нужно убедиться, что последовательность, в которой вы проходите, не пуста – например, or
с помощью одноэлементной последовательности, содержащей значение, которое вы хотели бы использовать в этом случае.
[EDITED после публикации, потому что Яков Белх любезно отметил в комментариях, что я написал “бесконечно большой”, где я должен был написать “бесконечно мало”.]
Ответ №5
Учитывая все комментарии выше, это может быть оболочка, подобная этой:
def max_safe(*args, **kwargs):
"""
Returns max element of an iterable.
Adds a `default` keyword for any version of python that do not support it
"""
if sys.version_info < (3, 4): # `default` supported since 3.4
if len(args) == 1:
arg = args[0]
if 'default' in kwargs:
default = kwargs.pop('default')
if not arg:
return default
# https://stackoverflow.com/questions/36157995#comment59954203_36158079
arg = list(arg)
if not arg:
return default
# if the `arg` was an iterator, it exhausted already
# so use a new list instead
return max(arg, **kwargs)
return max(*args, **kwargs)