Search code examples
pythonpython-3.xlistmin

Find minimum element and its position in list with Nones


I have a list of numbers and Nones like this:

l = [2., None, 3., 1., None, 2., None, 5.]

I want to get the minimum number and its index, while the Nones should simply be ignored. For the given example, the result would thus be:

(1., 3)

Of course, it is straightforward to write a function that does what I want but I would prefer some efficient built-in or at least high-level approach. I am particularly interested in solutions for Python 3, where the min-function does not accept None as an argument.


Solution

  • min((v,i) for i,v in enumerate(l) if v is not None)
    (1.0, 3) # (value, index)