Find the first element that meets the condition

J

jm.suresh

Hi,
I have a list and I want to find the first element that meets a
condition. I do not want to use 'filter', because I want to come out
of the iteration as soon as the first element is found.
I have implemented it this way, may be, there should be a built in
hiding somewhere in the standard libraries?

def exists(iterable, condition):
'''
Return the first element in iterble that meets the condition.
'''
for x in iterable:
if condition(x):
return x
raise Exception('No element meets the given condition.')


14

-
Suresh
 
T

Troy Melhase

I have implemented it this way, may be, there should be a built in
hiding somewhere in the standard libraries?

the itertools module might have what you're after. something similar
to your example:
14
 
P

Peter Otten

I have a list and I want to find the first element that meets a
condition. I do not want to use 'filter', because I want to come out
of the iteration as soon as the first element is found.
I have implemented it this way, may be, there should be a built in
hiding somewhere in the standard libraries?

def exists(iterable, condition):
'''
Return the first element in iterble that meets the condition.
'''
for x in iterable:
if condition(x):
return x
raise Exception('No element meets the given condition.')



14

If you are only interested in existence you can use any() (new in Python2.5)
True

Otherwise there is itertools.ifilter() a lazy variant of the filter()
builtin:
15

You may want to wrap the ifilter() call to get a more sensible exception,
say ValueError instead of StopIteration:

# untested
def findfirst(items, predicate=bool):
for item in itertools.ifilter(predicate, items):
return item
raise ValueError("No matching element")

Peter
 
P

Paul Rubin

I have a list and I want to find the first element that meets a
condition. I do not want to use 'filter', because I want to come out
of the iteration as soon as the first element is found.
I have implemented it this way, may be, there should be a built in
hiding somewhere in the standard libraries?

def exists(iterable, condition):

To check for existence, use any(condition, iterable). If you actually
want the first element, use itertools.ifilter(condition, iterable).next().
The suggestion of using dropwhile isn't so great because it actually
consumes the first match, so you have to write your condition to
stop immediately before the element you want, not always easy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top