Skip to content Skip to sidebar Skip to footer

Python Filter / Max Combo - Checking For Empty Iterator

(Using Python 3.1) I know this question has been asked many times for the general question of testing if iterator is empty; obviously, there's no neat solution to that (I guess for

Solution 1:

deff(lst):
  flt = filter(lambda x : x isnotNoneand x != 0, lst)
  try:
    returnmin(flt)
  except ValueError:
    returnNone

min throws ValueError when the sequence is empty. This follows the common "Easier to Ask for Forgiveness" paradigm.

EDIT: A reduce-based solution without exceptions

from functools import reduce
deff(lst):
  flt = filter(lambda x : x isnotNoneand x != 0, lst)
  m = next(flt, None)
  if m isNone:
    returnNonereturn reduce(min, flt, m)

Solution 2:

deff(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: returnmin(lst)
    else: returnNone

the list comprehension only allows items that don't evaluate to boolean false (which filters out 0 and None)

an empty list i.e. [] will evaluate to False, so "if lst:" will only trigger if the list has items

Solution 3:

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

Solution 4:

If you just want to check if the return of filter is empty, you might do (Python3)

len(list(filter(lambda e : e == 2, [1,2,3])))

But notice, hence filter is a generator if you this test twice, second time, you will receive a diferent result:

len(list(filter(lambda e : e == 2, [1,2,3]))) len(list(filter(lambda e : e == 2, [1,2,3])))

>>> 1

>>> 1

But:

f = filter(lambda e : e == 2, [1,2,3]) len(list(f)) len(list(f))

>>> 1

>>> 0

Solution 5:

t = [1,2,3]
ifany(filter(lambda x: x == 10, t)):
   print("found 10")

Post a Comment for "Python Filter / Max Combo - Checking For Empty Iterator"