Ghopper21
Ghopper21

Reputation: 10477

Is this is an efficient and pythonic way to see if any item in an iterable is true for a certain attribute?

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

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602115

You should use the built-in function any():

any_item_is_whatever = any(item.is_whatever() for item in items)

Upvotes: 12

Related Questions