473,701 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6007
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.dropw hile(lambda x:x<=13, r)
n.next()
14
Feb 25 '07 #2
jm*******@no.sp am.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(xrang e(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.ifilt er() a lazy variant of the filter()
builtin:
>>import itertools
items = iter(xrange(100 0)) # just to prove...
itertools.ifi lter(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.ifilt er(predicate, items):
return item
raise ValueError("No matching element")

Peter

Feb 25 '07 #3
"jm*******@no.s pam.gmail.com" <jm*******@gmai l.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.ifilt er(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
1737
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
2265
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 record and, when a condition is met, send an email. I suppose I could have some script inspect the latest record every x seconds and use sendmail, but I'm unfamiliar with scripting daemons on
8
2488
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 the '<' for the insert() and '==' operator for find() however it doesn't seem to be the case In fact it seems to only need to overload the '<' operator for BOTH functions (it simply ignores the '==' operator)
4
6481
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 algorithm, however, it partially sorts the data. I have a requirement that the data remain in the orginal order. Of course I could make a copy of the vector or array and then apply nth_element, but this would be expensive in memory and would require...
8
2137
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. Well, I have this issue where I may delete the map element in 3 different places: for ( map_key_pcmissile::iterator mit = World.Missiles.begin(); mit != World.Missiles.end(); ) { if ( /* Some Condition */ )
5
2575
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 it returns the iterator to the last element in the range, not to the last element in the container, to the last element in the range. That being said, how can we tell if find() has been successful in finding the element we need? Its easy when we...
0
1517
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 below). Imports System.IO Imports System.Data.OleDb
4
1675
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; I have a function that finds the maximum of an array of size 50. bool findMax50(float input)
4
9984
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 shortcut. Specifically, you have an Array, say an array of Ints. You have a maximum value, i.e. int someValue = Array.Max(); and you would like to know which ith cell of the Array holds this value. How to do this without iterating the entire...
0
8736
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8977
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6571
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5904
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4410
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3102
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2035
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.