Valueerror min arg is an empty sequence ошибка

There is no problem with the syntax. It’s certainly unusual to have two if clauses, but it’s allowed. Consider:

print(min(x for x in range(1,300) if x % 3 == 0 if x % 5 == 0))

Output:

15

However:

print(min(x for x in range(1,300) if x % 2 != 0 if x % 2 != 1))

Output:

ValueError: min() arg is an empty sequence

There are no integers that are both odd and even, so there are no values for min to see, so it throws an exception.

I deduce that in your code, there are no values that pass both conditions. Python doesn’t allow you to compute «the minimum of no values», mainly because it makes no sense.

You have to decide what you want to do in the case where there is no minimum because there are no values greater than 0. For example, if you don’t want to return k in that case then I might re-write your code something like this:

for k in range(4):
    if k != i and is_visited[k] is False:
        if matr_sum[i][k] > 0 and matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0):
            return k

It might not be obvious why this helps, but assuming matr_sum[i] is a list or similar, then once we know matr_sum[i][k] > 0 then we know the generator passed to min isn’t empty, so we won’t get an exception. Whereas if matr_sum[i][k] <= 0, then it certainly isn’t equal to the smallest positive value, so there’s no need to compute the min at all. Another way to write that would be:

if matr_sum[i][k] > 0 and not any(0 < x < matr_sum[i][k] for x in matr_sum[i])

Actually, I’d normally write if not is_visited[k], but I leave it as is False since I don’t know whether changing it would change the behaviour of your code.

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

To solve this error, ensure you only pass iterables to the min() 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: 
    min_value = min(iterable)

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


Table of contents

  • ValueError: min() arg is an empty sequence
    • What is a Value Error in Python?
    • Using min() in Python
  • Example: Returning a Minimum Value from a List using min() in Python
    • Solution

ValueError: min() 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: min() arg is an empty sequence is a ValueError because while an iterable is a valid type of object to pass to the min() function, the value it contains is not valid.

Using min() in Python

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

var_1 = 2
var_2 = 7
var_3 = 1

min_val = min(var_1, var_2, var_2)

print(min_val)

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

2

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

string = "research"

min_val = min(string)

print(min_val)

Let’s run the code to get the result:

s

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

Example: Returning a Minimum Value from a List using min() in Python

Let’s write a program that finds the minimum boxes sold of different vegetables across a week. First, we will define a list of vegetables:

vegetables = [

{"name":"Spinach", "boxes_sold":[10, 4, 20, 50, 29, 100, 70]},

{"name":"Asparagus", "boxes_sold":[20, 5, 10, 50, 90, 10, 50]},

{"name":"Broccolli", "boxes_sold":[33, 10, 8, 7, 34, 50, 21]},

{"name":"Carrot", "boxes_sold":[]}

]

The list contains four dictionaries. Each dictionary contains the name of a vegetable and a list of the number of boxes sold over seven days. The carrot order recently arrived, meaning no carrots were sold. Next, we will iterate over the list using a for loop and find the smallest amount of boxes sold for each vegetable over seven days.

for v in vegetables:

    smallest_boxes_sold = min(v["boxes_sold"])

    print("The smallest amount of {} boxes sold this week is {}.".format(v["name"], smallest_boxes_sold))

We use the min() function in the above code to get the smallest item in the boxes_sold list. Let’s run the code to get the result:

The smallest amount of Spinach boxes sold this week is 4.
The smallest amount of Asparagus boxes sold this week is 5.
The smallest amount of Broccolli boxes sold this week is 7.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [9], in <cell line: 1>()
      1 for v in vegetables:
----> 3     smallest_boxes_sold = min(v["boxes_sold"])
      5     print("The smallest amount of {} boxes sold this week is {}.".format(v["name"], smallest_boxes_sold))

ValueError: min() arg is an empty sequence

The program raises the ValueError because the boxes_sold list for Carrot is empty.

Solution

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

for v in vegetables:

    if len(v["boxes_sold"]) > 0:

        smallest_boxes_sold = min(v["boxes_sold"])
        print("The smallest amount of {} boxes sold this week is {}.".format(v["name"], smallest_boxes_sold))

    else:

        print("No {} boxes were sold this week.".format(v["name"]))
The smallest amount of Spinach boxes sold this week is 100.
The smallest amount of Asparagus boxes sold this week is 90.
The smallest amount of Broccolli boxes sold this week is 50.
No Carrot boxes were sold this week.

The program successfully prints the minimum amount of boxes sold for Spinach, Asparagus, and Broccolli. The boxes_sold list for Carrot is empty; therefore, the program informs us that no boxes of carrots were sold this week.

Summary

Congratulations on reading to the end of this tutorial! The error: “ValueError: min() arg is an empty sequence” occurs when you pass an empty list as an argument to the min() function. The min() function cannot find the smallest 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 min() function.

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!

To fix the ValueError: min() arg is an empty sequence in Python, there are some solutions we have effectively tested: Initialize a list of values, pass the Default value to the function, and use if and try/except statements to check for exceptions. Follow the article to understand better.

The min() function is a built-in function in Python.

The min() function will return the smallest value in an iterable, or the smallest in a parameter passed.

Syntax:

min( value1, value2, value3, … )

Parameters:

  • value1, value2, value3: is a numeric, character, or string expression.

The ValueError: min() arg is an empty sequence in Python that happens when the min() function takes an empty sequence as an argument.

Example: 

emptyList = [ ]

# Use the min() function
print(min(emptyList))

Output:

Traceback (most recent call last):
  File "./prog.py", line 4, in <module>
ValueError: min() arg is an empty sequence

How to solve this error?

Initialize a list of elements

The argument of the min() function is an empty list that will cause an error, so to fix it, you just need to initialize a list of elements. Now the list as an argument to the min() function will not get an error. 

Example:

  • Initialize a list of elements.
  • Use the min() function to find the smallest element in the list.
# Initialize a list with elements
valuesList = [1, 2, 3, 4]

# Use the min() function
print('The smallest element in the list:', min(valuesList))

Output:

The smallest element in the list: 1

Pass the Default value to the min() function

You can fix the error by passing the value ‘default’ to the min() function. This will replace the default value of an empty list.

Example:

  • Declare an empty list.
  • The min() function with the ‘default=0’ value is used to fix the error.
  • The min() function will return the value of the ‘default’ keyword argument.
myList = []

# Use the min() function with the default value = 0 argument
print(min(myList, default = 0))

Output:

0

You can pass the value default = None as the min() function argument.

Example:

myList = []

# Use the min() function with the default value = None argument
print(min(myList, default = None))

Output:

None

The min() function will return the value of the ‘default’ keyword argument. (If the list has the smallest value, the min() function will return the smallest value).

Use the command if

Before passing an argument to min(), you need to check the length of that argument to avoid an error.

Example:

  • Declare an empty list.
  • Use the if statement to check if the list is empty or not.
myList = []

if myList:
   print(min(myList))
else:
   print('List is empty')

Output:

List is empty

Use len() function.

You can check if a list is empty by using len() and then setting it as a min() function parameter.

Example:

  • Declare a list is empty.
  • Use len() function to check if the list is empty or not. If len() returns zero, the list is empty.
myList = [] 

# Use len() function to check for empty list
if len(myList) == 0:
    print('List is empty')
else:
    print(len(myList))

Output:

List is empty

Use the or operator

Example:

  • Initialize an empty list and a list of elements.
  • The or operator will replace the empty list with a list containing the elements.
firstList = [] 
secondList = [1, 2, 3, 4]

# Use the or operator replace the empty list with a list containing the elements
print("Smallest value:", min(firstList or secondList))

Output:

Smallest value: 1

Summary

The ValueError: min() arg is an empty sequence in Python that is fixed. I think the most suitable way to solve this error is to avoid the empty string initialization. Through this article, I hope you will learn from your experience using the min() function. If you find this helpful website, visit it to read more exciting lessons.

Maybe you are interested:

  • ValueError: invalid literal for int() with base 10 in Python
  • ValueError: I/O operation on closed file in Python
  • ValueError: object too deep for desired array

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

The “ValueError: min() arg is an empty sequence” error in Python occurs when you try to call the min() function on an empty sequence, such as a list or tuple.

To solve this error, you need to make sure that you pass a non-empty sequence or a default value. This article shows you how it works.

The min() function is a built-in function in Python that returns the smallest element in a sequence as shown below:

list = [8, 4, 10, 2]

result = min(list)

print(result)  # 2

However, if you try to call min() on an empty sequence, the function has nothing to compare, and Python will raise a “ValueError: min() arg is an empty sequence” to notify you of this issue.

The following code:

list = []

# ❗️ValueError: min() arg is an empty sequence
result = min(list)  

Will produce the output below:

To fix this error, you need to make sure that the sequence passed to min() is not empty.

You can do this by checking the length of the sequence before calling min(), or by adding the default argument for the function when the sequence is empty.

See the example below:

# example 1: pass empty list with default value
list = []

result = min(list, default=0)

print(result)  # 0

# example 2: pass a list with default value
list = [7, 9, 10, 5]

result = min(list, default=0)

print(result)  # 5

When you pass a default argument, Python will assign the default value when the list is empty.

You can pass any type of data as the default argument, like a string or another list:

list = []

# pass a list as the default value
result = min(list, default=[1, 2, 3])

print(result)  # [1, 2, 3]

Alternatively, you can also use an if .. else conditional and call the min() function only when the list is not empty.

When the len() of the list is greater than 0, call the min() function as shown below:

list = []

if len(list) > 0:
    result = min(list)
else:
    result = 9

The code above will assign the number 9 as the value of the result variable when the list is empty.

Finally, you can also add the try .. except block like this:

list = []

try:
    result = min(list)
except ValueError:
    print("An error occurred")
    result = 9

print(result)  # 9

The except block above will be run whenever the code in the try block raises a ValueError. This keeps the code running since Python knows what to do when the error happens.

You are free to continue the code above to fit your project.

Conclusion

The Python “ValueError: min() arg is an empty sequence” error is raised when you pass an empty list as an argument to the min() function.

To solve this error, you need to make sure that the list argument has at least one valid element. You can also pass a default argument to the function that will be used as the default value should the sequence is empty.

Now you’ve seen how to fix this error like a real Python pro! 👍

Keep in mind that the min() function may raise other errors if the elements of the sequence are not comparable.

For example, if the sequence contains elements of different types, such as strings and integers, the function will raise a TypeError: < not supported between instances of int and str error.

Besides the min() function, the max() function also has the ValueError exception with the same solution.

есть некая функция которая возвращает кортеж из 3 значений.первые 2 значения всегда присутствуют .Но вот третьего может и не быть. Если такое случается получается даная ошибка min() arg is an empty sequence.Єто значение очень важное и не хочеться ради него что то создавать новое.В кратце функция выглядит вот так.Заранее спасибо.

def get_price(bt_object, pair, min_price, sum_limit=0):

    sells = bt_object.get_sell_trades(pair)

    current_min_price = min(x) if....

    current_min_price1 = min(x) if....

    BUY_UP_PRICE = min(x) if.....    ошибка arg is an empty sequence если такого значения нет.

    return (current_min_price,current_min_price1,BUY_UP_PRICE)

Понравилась статья? Поделить с друзьями:
  • Vaillant ошибка ser в котле
  • Vaillant ошибка f20 как сбросить
  • Vaillant газовая колонка ошибка f22
  • Vaillant turbotec pro ошибка f75
  • Vaillant turbotec pro ошибка f29 что делать