Pythonic way of checking if a condition holds for any element of a list

PythonList

Python Problem Overview


I have a list in Python, and I want to check if any elements are negative. Specman has the has() method for lists which does:

x: list of uint;
if (x.has(it < 0)) {
    // do something
};

Where it is a Specman keyword mapped to each element of the list in turn.

I find this rather elegant. I looked through the [Python documentation][1] and couldn't find anything similar. The best I could come up with was:

if (True in [t < 0 for t in x]):
    # do something

I find this rather inelegant. Is there a better way to do this in Python?

[1]: http://docs.python.org/library/stdtypes.html#typesseq-mutable "Python Built-in Types"

Python Solutions


Solution 1 - Python

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

Solution 2 - Python

Use any().

if any(t < 0 for t in x):
    # do something

Solution 3 - Python

Python has a built in http://docs.python.org/library/functions.html#any">any()</a> function for exactly this purpose.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan FellmanView Question on Stackoverflow
Solution 1 - PythonKenView Answer on Stackoverflow
Solution 2 - PythonDaniel PrydenView Answer on Stackoverflow
Solution 3 - PythonAmandasaurusView Answer on Stackoverflow