I have a function. matchCondition(a)
, which takes an integer and either returns True or False.
I have a list of 10 integers. I want to return the first item in the list (in the same order as the original list) that has matchCondition
returning True.
As pythonically as possible.
The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input.
For this, we will use the count() method. The count() method, when invoked on a list, takes the element as input argument and returns the number of times the element is present in the list. For checking if the list contains duplicate elements, we will count the frequency of each element.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
first is an MIT-licensed Python package with a simple function that returns the first true value from an iterable, or None if there is none. If you need more power, you can also supply a key function that is used to judge the truth value of the element or a default value if None doesn't fit your use case.
next(x for x in lst if matchCondition(x))
should work, but it will raise StopIteration
if none of the elements in the list match. You can suppress that by supplying a second argument to next
:
next((x for x in lst if matchCondition(x)), None)
which will return None
if nothing matches.
Demo:
>>> next(x for x in range(10) if x == 7) #This is a silly way to write 7 ... 7 >>> next(x for x in range(10) if x == 11) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> next((x for x in range(10) if x == 7), None) 7 >>> print next((x for x in range(10) if x == 11), None) None
Finally, just for completeness, if you want all the items that match in the list, that is what the builtin filter
function is for:
all_matching = filter(matchCondition,lst)
In python2.x, this returns a list, but in python3.x, it returns an iterable object.
Use the break
statement:
for x in lis: if matchCondition(x): print x break #condition met now break out of the loop
now x
contains the item you wanted.
proof:
>>> for x in xrange(10): ....: if x==5: ....: break ....: >>> x >>> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With