Python filter / max combo - check for empty iterator

(using Python 3.1)

I know this question has been asked many times for a general testing question if the iterator is empty; obviously there is no neat solution for this (I think, for some reason, the iterator really does not know if it is empty until it asks to return its next value).

I have a specific example, however I was hoping that I could make a clean and Pythonic code out of it:

#lst is an arbitrary iterable
#f must return the smallest non-zero element, or return None if empty
def f(lst):
  flt = filter(lambda x : x is not None and x != 0, lst)
  if # somehow check that flt is empty
    return None
  return min(flt)

Is there a better way to do this?

EDIT: sorry for the dumb designation. A function parameter is indeed an iterable, not a list.

+4
source share
3 answers
def f(lst):
  flt = filter(lambda x : x is not None and x != 0, lst)
  try:
    return min(flt)
  except ValueError:
    return None

min ValueError, . " ".

EDIT:

from functools import reduce
def f(lst):
  flt = filter(lambda x : x is not None and x != 0, lst)
  m = next(flt, None)
  if m is None:
    return None
  return reduce(min, flt, m)
+4
def f(lst):
    # if you want the exact same filtering as the original, you could use
    # lst = [item for item in lst if (item is not None and item != 0)]

    lst = [item for item in lst if item]
    if lst: return min(lst)
    else: return None

, boolean false ( 0 None)

i.e. [] False, "if lst:" ,

+1

you can go and to reduce expression return reduce(lambda a,b: a<b and a or b,x) or None

0
source

All Articles