Max arg is an empty sequence python ошибка

Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

Another thing is that since you’re iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

Lastly dict.get is a method not a list or dictionary so you can’t use [] with it:

Correct way is:

if frequencies.get(name):

And Pythonic way is:

if name in frequencies:

The Pythonic way to get the frequency of items is to use collections.Counter:

from collections import Counter   #Add this at the top of file.

def clkFindMost(self, parent):

        #self.listMyData = []   
        if self.listMyData:
           frequencies = Counter(self.listMyData)
           self.txtResults.Value = max(frequencies, key=frequencies.get)
        else:
           self.txtResults.Value = '' 

max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

>>> lst = []
>>> max(lst)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
    mx = max(lst)
else:
    #Handle this here

If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can’t use if on them directly:

>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
       mx = max(lst)
    else:
      #Handle this here   

Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

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!

I am a fairly experienced coder, but I am not able to understand this problem within python. The text file that it refers to is laid out as

Jeff 4 7 7
Rich 2 1 9
Chris 4 6 5

Yet when I run the code it works out the first two sets of data but not the last. The code is:

with open(classno, 'r') as f: #it doesn't write last score and 
        for line in f:
            nums_str = line.split()[1:]
            nums = [int(n) for n in nums_str]
            max_in_line = max(nums) #uses last score of it need to combine
            print (max_in_line)
            with open('class11.txt', 'r') as f:
                parts = line.split()
                if len(parts) > 2:
                    name = str(parts[0])
                    f = open(classno, 'a')
                    f.write(("n") + (name) + (" ") + str(max_in_line))

        f.close()

…but on the final line of the text file it says:

max() arg is an empty sequence

Kyle Strand's user avatar

Kyle Strand

15.8k6 gold badges72 silver badges165 bronze badges

asked Jan 19, 2015 at 19:02

dfsfsdfdsfs's user avatar

2

Probably you have a newline character at the end of your file, so you’re reading in a blank line. Try this:

for line in f:
    if line: 
        ....

answered Jan 19, 2015 at 19:05

Adam Hughes's user avatar

Adam HughesAdam Hughes

14.4k11 gold badges80 silver badges122 bronze badges

You redefine f in the most outer with

with open(classno, 'r') as f:

In inner loop:

with open('class11.txt', 'r') as f:

Give different names to these vars.

answered Jan 19, 2015 at 19:06

bav's user avatar

bavbav

1,54313 silver badges13 bronze badges

2

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”.

Get offers and scholarships from top coding schools illustration

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

Email

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!

Python

max()

is an inbuilt function that can accept an iterable object and return the largest value from it. Instead of an iterable object, we can also pass more than one argument value to the

max()

function, and it will return the largest value. But if we pass an empty iterable object like an empty list, empty string, empty tuple, or empty set in the max function, it will throw the Error

ValueError: max() arg is an empty sequence

.

In this Python tutorial, we will discuss this error statement in detail and learn how to solve it. We will also walk through an example that will demonstrate this error, and in the solution section, we will solve that error.

In Python, we often use

max()

and min() functions to get the largest and smallest value from a list, tuple, and string. And instead of writing a simple comparison operation, we can use the max() or min() methods to find out the minimum and maximum values.

The max() function will only work if we pass a non-empty iterable object as an argument, and all the values of that iterable object must be of the same data type. If we pass an empty iterable object as an argument value to the max() method, we will encounter the

ValueError: max() arg is an empty sequence

Error.

Now Let’s discuss the Error statement in detail. The Error statement can further be divided into two parts

  1. ValueError (Exception Type)
  2. max() arg is an empty sequence


1. ValueError

The ValueError is one of the Python standard exceptions. It is raised in a Python program when we specify the right argument data type to a function, but the value of that argument is wrong. We can pass iterable objects to the max() method, but if the iterable object is empty, it raises the ValueError Exception.


2. max() arg is an empty sequence


max() arg is an empty sequence

is the Error Message, it is raised along with the ValueError to tell the programmer more specific detail about the error. This error message tells us that the iterable sequential argument we passed to the max() method is an empty object.


Example

my_nums = []  #empty string

largest_num = max(my_num)


Output

Traceback (most recent call last):
   File "<stdin>", line 3, in <module>
ValueError: max() arg is an empty sequence


Common Example Scenario

Now we know why this error raises in a Python program. Let’s discuss an example of how we can solve this error. We have a

prices

list that is supposed to contain the prices of the different products. And we need to create

a program

that asks the user to enter all the prices of the product they brought from the store. And return the largest value price from the

prices

list.

Let’s say if the user buys

0

products from the store, in that case, if we apply the max() method on our

prices

list we will get the error.


Error Example

# list of all prices
prices =[]

# number of products
products = 0

for number in range(products):
    price = float(input(f"Enter the price of product {number +1}"))
    # append the price in the prices list
    prices.append(price)

# find the largest price
most_expensive = max(prices)

print("The most expensive product price is: ",most_expensive )


Output

Traceback (most recent call last):
  File "C:UserstsmehraDesktopcodemain.py", line 13, in 
    most_expensive = max(prices)
ValueError: max() arg is an empty sequence


Break the code

In this example, we are getting this error because the list

prices

passed to the

max()

function is empty. The value of products is 0. That’s why we are not able to append values to the

prices

list, which makes a list empty, and the empty list causes the error with the max function.


Solution

If you encounter such situations where the list object depends on some other statements, it might be possible that the iterable object can be empty. In such cases, we can specify a default argument value to the max function that will be returned if the iterable object is empty.

max(iterable_object, default = value)


Example Solution

# list of all prices
prices =[]

# number of products
products = 0

for number in range(products):
    price = float(input(f"Enter the price of product {number +1}: "))
    # append the price in the prices list
    prices.append(price)

# find the largest price
most_expensive = max(prices, default = 0.0)

print("The most expensive product price is: ",most_expensive )


Output

The most expensive product price is: 0.0


Wrapping Up!

The Error

ValueError: max() arg is an empty sequence

raises in a Python program when we pass an empty iterable object to the max method. To solve this error, we need to make sure that we are passing a non-empty iterable object to the max() method. If the program is all dynamic and the iterable object elements depend on the program run, there we can specify the default argument in the max() method after the iterable object, so in the case of an empty iterable object, the max() method return the default value, not the error.

If you are still getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python SyntaxError: non-default argument follows default argument Solution

  • Install Python package using Jupyter Notebook

  • Python FileNotFoundError: [Errno 2] No such file or directory Solution

  • Online Python Compiler

  • Python RecursionError: maximum recursion depth exceeded while calling a Python object

  • How to run a python script?

  • Python TypeError: can only join an iterable Solution

  • What is Python used for?

  • Python SyntaxError: cannot assign to operator Solution

  • Encrypt and Decrypt Files in Python

  • Mavic mini ошибка 30008
  • Maxer блок управления murat machine ca 747 ошибки 7
  • Max retries exceeded with url python ошибка
  • Maunfeld стиральная машина ошибка 777
  • Max pro 200 ошибка 027