473,327 Members | 1,919 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Find the first element that meets the condition

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.')
>>exists(xrange(1000), lambda x: x>13)
14

-
Suresh

Feb 25 '07 #1
3 5965
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:
>>import itertools
r = iter(range(100))
n = itertools.dropwhile(lambda x:x<=13, r)
n.next()
14
Feb 25 '07 #2
jm*******@no.spam.gmail.com wrote:
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.')
>>>exists(xrange(1000), lambda x: x>13)
14
If you are only interested in existence you can use any() (new in Python2.5)
>>any(x>13 for x in xrange(1000))
True

Otherwise there is itertools.ifilter() a lazy variant of the filter()
builtin:
>>import itertools
items = iter(xrange(1000)) # just to prove...
itertools.ifilter(lambda x: x 13, items).next()
14
>>items.next() # that ifilter has consumed only the first 15 items
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

Feb 25 '07 #3
"jm*******@no.spam.gmail.com" <jm*******@gmail.comwrites:
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.
Feb 25 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Neal D. Becker | last post by:
What is an efficient way to find the first element in a sequence meeting some condition? For example, the first number > x in a list of numbers.
0
by: JT | last post by:
Hi, I'm sure this isn't a hard one, can someone help? I'm adding a new record to a MySQL database every x seconds. I need to be able to inspect the content of a certain field in this incoming...
8
by: Rom | last post by:
I'm a bit confused as to how the STL set works with the <setname>.insert() and <setname>.find() functions Compiler used : CodeWarrior 5.0 My intial interpretation was that I needed to overload...
4
by: Code4u | last post by:
I need to write an algorithm that sheds the outliers in a large data set, for example, I might want to ignore the smallest 2% of values and find the next smallest. Boost has a nth_element...
8
by: Jim Langston | last post by:
There's the thing about iterating though a map or vector when you may delete one of the elements, where you simply assign the iterator to the map.erase() statement or increment it if you don't. ...
5
by: Draw | last post by:
Hi All, Just a thought, about the find() algorithm in the C++ STL. I read that the find algorithm can take a range of iterators. If it does not find the element it is looking for in that range...
0
by: RN | last post by:
Hi everyone, First please let me explain. I am attempting to store pdf files in an MS Access DB (2000) and I have written a subroutine to do this. My code seems to work perfectly (see code...
4
by: lightaiyee | last post by:
Dear Gurus, I would like to implement a function that computes the number of times a certain condition is met in a global array. For example, I have an global array of size 500. float array;...
4
by: raylopez99 | last post by:
I would like to know if there's a quick "Linq" way to find the index of an array having a particular value. I can do this the long way by sequential iteration, but would like to know if there's a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.