Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 1000
Ghopper21 Avatar asked Aug 09 '12 17:08

Ghopper21


People also ask

How do you know if an item is iterable?

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.

How do you check if all elements of a list are true?

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.


1 Answers

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

any_item_is_whatever = any(item.is_whatever() for item in items)
like image 73
Sven Marnach Avatar answered Nov 08 '22 13:11

Sven Marnach