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!

In Python, an inbuilt function “max()” is used in a program to find the maximum value of the input sequence. Trying to execute the “max()” function on an empty sequence will throw the “max() arg is an empty sequence” error in Python. To resolve this error, various solutions are provided by Python.

This Python write-up will give you the reason and various solutions for “ValueError: max() arg is an empty sequence”.

  • Reason: Passing Empty Sequence
  • Solution 1: Passing Sequence With Values
  • Solution 2: Using the “default” Parameter
  • Solution 3: Using len() Function
  • Solution 4: Using try-except

Reason: Passing Empty Sequence

One of the prominent reasons which cause this error in Python programs is initializing an empty sequence as an argument to the “max()” function.

The above snippet shows “ValueError” because an empty dictionary sequence “dict_value” is passed inside the max() function.

Solution 1: Passing Sequence With Values

To resolve this error, a sequence containing at least one value must be passed to the max() function.

Code:

dict_value = {5:'Lily', 10: 'John'}
Output = max(dict_value)
print(Output)

In the above code, a sequence “dict_value” with multiple elements is initialized in the program. The “max()” function accepts the “dict_value” variable as an argument and returns the dictionary key having the maximum value.

Output:

The above output shows that the max() function retrieves the maximum dictionary key from the input dictionary sequence.

Solution 2: Using the “default” Parameter

This error can also be overcome in Python by assigning the “default” parameter value to “0”.

Code:

dict_value = {}
Output = max(dict_value, default=0)
print(Output)

In the above code, the dictionary variable “dict_value” is initialized with an empty value. The “max()” function accepts two arguments, the input variable “dict_Value” and the default parameter “default=0”. Whenever the input sequence is empty, the “max()” function returns the value “0” by default.

Output:

The above output verified that the input sequence is empty.

Solution 3: Using len() Function

To overcome this error, the “len()” function is also used in Python programs. The “len()” function is used along with the “if-else” statement to get the length and perform the operation on the input sequence based on the specified condition.

Code;

dict_value = {}
if len(dict_value)>0:
    Output = max(dict_value)
    print(Output)
else:
    print('Input Sequence is Empty')

In the above code, the “dict_value” dictionary sequence variable is initialized in the program. The “max()” function will be used on the input sequences if the length of the sequence is greater than “0”; otherwise, the “else” block will execute.

Output:

The above output shows that the input sequence is empty.

Solution 4: Using try-except

The “try-except” is also used to handle the “ValueError: max() arg is an empty sequence” in Python. Let’s see it via the following code:

Code:

dict_value = {}

try: 
    Output = max(dict_value)
    print(Output)
except:
    print('Input Sequence is Empty')

In the above code, the variable “dict_value” is initialized in the program. The “try” block executes its code and finds the maximum value of the input sequence using the “max()” function. But if the error arises, the “except” block will execute its code.

Output:

The above output shows that the “except” block executes its code because the input sequence is empty.

Conclusion

The “ValueError: max() arg is an empty sequence” occurs when a user tries to pass an empty sequence as an argument to the max() function. To resolve this error, various solutions are used in Python, such as passing sequence value, using default parameters, using the len() function, and using the try-except block. The “len()” function can be utilized along with the “if-else” statement to resolve this error. This article delivered multiple solutions for the error “max() arg is an empty sequence” in Python.

Ad

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

Find the right bootcamp for you

ck-logo

X

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.

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:\Users\tsmehra\Desktop\code\main.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

Понравилась статья? Поделить с друзьями:
  • Mc3092 probe open ошибка
  • Mazda mpv ошибка p0031
  • Mavic mini 2 ошибка 30210
  • Mavic mini ошибка 40002
  • Mc3001 ошибка fanuc