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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With