Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return 0 or something else if min(list) raises ValueError?

Tags:

python

I have a list value, my_list, that I would want to get its minimum value:

min_value = min(my_list)

This works fine if my_list is not empty but raises ValueError if the list is empty.

Is there any way I can return something else in a very Pythonic way if my_list is empty and also have the ValueError arrested without having to check with if(like shown below):

if my_list:
    min_value = min(my_list)

I want a one line thing. Something like:

min_value = min(my_list) or another_value
like image 430
Yax Avatar asked Sep 02 '25 02:09

Yax


1 Answers

In Python 3.4, you can use the new default keyword:

min_value = min(my_list, default=0)

In older versions, a simple conditional expression can be used:

min_value = min(my_list) if my_list else 0  # Empty lists evaluate to False

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!