Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a reason - an iterator doesn't really know if it's empty until it's asked to return its next value).

I have a specific example, however, and was hoping I can make 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 any better way to do that?

EDIT: sorry for the stupid notation. The parameter to the function is indeed an arbitrary iterable, rather than a list.

like image 261
max Avatar asked Oct 15 '10 06:10

max


People also ask

How do you iterate through a filter object in Python?

Filtering Iterables With filterfalse() It takes an iterable as argument and returns a new iterator that yields the items for which the decision function returns a false result. If you use None as the first argument to filterfalse() , then you get the items that are falsy.

How do I check if a list is empty in Python?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.

What does filter () do in Python?

filter() in python The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. syntax: filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not.


1 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 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
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)
like image 200
Matthew Flaschen Avatar answered Oct 24 '22 16:10

Matthew Flaschen