Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: min(None, x)

I would like to perform the following:

a=max(a,3) b=min(b,3) 

However sometimes a and b may be None.
I was happy to discover that in the case of max it works out nicely, giving my required result 3, however if b is None, b remains None...

Anyone can think of an elegant little trick to make min return the number in case one of the arguments in None?

like image 869
Jonathan Livni Avatar asked Jun 06 '11 16:06

Jonathan Livni


2 Answers

Why don't you just create a generator without None values? It's simplier and cleaner.

>>> l=[None ,3] >>> min(i for i in l if i is not None) 3 
like image 90
utdemir Avatar answered Sep 23 '22 14:09

utdemir


My solution for Python 3 (3.4 and greater):

min((x for x in lst if x is not None), default=None) max((x for x in lst if x is not None), default=None) 
like image 21
R1tschY Avatar answered Sep 23 '22 14:09

R1tschY