Reputation: 10477
Say you have an iterable sequence of thing
objects called things
. Each thing
has a method is_whatever()
that returns True if it fulfills the "whatever" criteria. I want to efficiently find out if any item in things
is whatever.
This is what I'm doing now:
any_item_is_whatever = True in (item.is_whatever() for item in items)
Is that an efficient way to do it, i.e. Python will stop generating items from the iterable as soon as it finds the first True result? Stylistically, is it pythonic?
Upvotes: 5
Views: 96
Reputation: 602115
You should use the built-in function any()
:
any_item_is_whatever = any(item.is_whatever() for item in items)
Upvotes: 12