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?
As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn't. This is more accurate than using isinstance(x, abc. Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.
The Python all() function returns true if all the elements of a given iterable (List, Dictionary, Tuple, set, etc.) are True, else it returns False. It also returns True if the iterable object is empty.
You should use the built-in function any()
:
any_item_is_whatever = any(item.is_whatever() for item in items)
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