if does not evaluate

Terry Reedy tjreedy at udel.edu
Fri Jun 11 17:18:06 CEST 2004


"Jim Newton" <jimka at rdrop.com> wrote in message
news:2ituufFrgqhaU1 at uni-berlin.de...
> if i have a list x and a function f how do i know if
> there is an element of x on which f returns something
> other than False?

If I understand you correctly, you want something like

somexf=False
for i in x:
    if f(i):
        somexf = True
        break

# somexf == <for some item in x f is true>

You are correct, filter() and the equivalent list comp give all items for
which f is true.
They do not break/return on encountering the first one.  As a function, the
above is

def some(iterable, f):
  for item in iterable:
    if f(item): return True
  return False

You can easily modify this to instead return item or None.

Terry J. Reedy







More information about the Python-list mailing list