Python: min(None, x)

Solution 1:

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

Solution 2:

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)

Solution 3:

A solution for the Python 3

Code:

# variable lst is your sequence

min(filter(lambda x: x is not None, lst)) if any(lst) else None

Examples:

In [3]: lst = [None, 1, None]

In [4]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[4]: 1

In [5]: lst = [-4, None, 11]

In [6]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[6]: -4

In [7]: lst = [0, 7, -79]

In [8]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[8]: -79

In [9]: lst = [None, None, None]

In [10]: min(filter(lambda x: x is not None, lst)) if any(lst) else None

In [11]: print(min(filter(lambda x: x is not None, lst)) if any(lst) else None)
None

Notes:

Worked in sequence presents as numbers as well as None. If all values is None min() raise exception

ValueError: min() arg is an empty sequence

This code resolve this problem at all

Pros:

  1. Worked if None presents in sequence
  2. Worked on Python 3
  3. max() will be work also

Cons

  1. Need more than one non-zero variable in the list. i.e. [0,None] fails.
  2. Need a variable (example lst) or need duplicate the sequence