I want to stop the iteration when I find the first True, like this:
>> for x in ['a', 'b', 1, 2, 3]:
>> if isinstance(x, int):
>> print(x)
>> break
1
How can I do the same thing but with list comprehension for-loop?
I want to stop the iteration when I find the first True, like this:
>> for x in ['a', 'b', 1, 2, 3]:
>> if isinstance(x, int):
>> print(x)
>> break
1
How can I do the same thing but with list comprehension for-loop?
You can use next
on a generator expression to return the first True
instance:
x = next((a for a in ['a', 'b', 1, 2, 3] if isinstance(a, int)), None)
print(x)
1
x = next((a for a in ['a', 'b'] if isinstance(a, int)), None)
print(x)
None
Where the second argument is a return value that allows you to avoid StopIteration
errors
This can be reduced to the filter
operator as shown by the itertools recipe above:
x = next(filter(int.__instancecheck__, ['a', 'b', 1, 2, 3]), None)
Unfortunately, there is no built-in mechanism for finding the first element of a list that matches a predicate. There is any
, which you can use to determine if such an element exists, but that won't tell you what element it was.
any(isinstance(x, int) for x in ['a', 'b', 1, 2, 3])
Luckily, itertools
provides a variety of functions for when you want to do some operation on a list or any other iterable.
The function you're looking for isn't built in to the module, but the documentation provides definitions for a handful of functions, including this one, as the itertools recipes. The function you need is named first_true
. Just copy the definition, and:
def first_true(iterabe, default=False, pred=None):
return next(filter(pred, iterable), default)
x = first_true(['a', 'b', 1, 2, 3], pred=int.__instancecheck__)
If nothing in the list matches the predicate, first_true
will return False
. If you want a different behavior, you can modify the function. The other recipes might be a good place to start if you want to understand how to work with iterators in the itertools style.
If you're trying to do more complicated processing in the loop than just finding the first matching element, you're probably better off using a proper for
loop, though. List comprehensions and generator expressions are good as a replacement for map and filter, and itertools provides more general operations on iterables, but they aren't meant to stand in for real loop logic.