158

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?


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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

3 Answers3

254

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):
Ken
  • 5,337
  • 3
  • 28
  • 19
38

Use any().

if any(t < 0 for t in x):
    # do something
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
  • 1
    Can anyone please explain why we don't wrap the list comprehension in brackets, like so: `if any([t < 0 for t in x])` ? – Andrew Anderson Oct 10 '22 at 18:57
  • I believe that's because it's a generator expression, not list comprehension. Here's [more about generator expressions](https://stackoverflow.com/questions/364802/how-exactly-does-a-generator-comprehension-work). – piedpiper Dec 21 '22 at 01:00
11

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

Amandasaurus
  • 58,203
  • 71
  • 188
  • 248