Nathan Fellman
Nathan Fellman

Reputation: 127428

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

I have a list in Python, and I want to check if any elements are negative. Is there a simple function or syntax I can use to apply the "is negative" check to all the elements, and see if any of them is negative? I looked through the documentation 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?


See also How to check if all elements of a list match a condition? for checking the condition for all elements. Keep in mind that "any" and "all" checks are related through De Morgan's law, just as "or" and "and" are related.

Existing answers here use the built-in function any to do the iteration. See How do Python's any and all functions work? for an explanation of any and its counterpart, all.

If the condition you want to check is "is found in another container", see How to check if one of the following items is in a list? and its counterpart, How to check if all of the following items are in a list?. Using any and all will work, but more efficient solutions are possible.

Upvotes: 170

Views: 181579

Answers (3)

Daniel Pryden
Daniel Pryden

Reputation: 60957

Use any().

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

Upvotes: 42

Ken
Ken

Reputation: 5581

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):

Upvotes: 275

Amandasaurus
Amandasaurus

Reputation: 60709

Python has a built in any() function for exactly this purpose.

Upvotes: 12

Related Questions