Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?


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.

like image 335
Nathan Fellman Avatar asked Oct 09 '22 07:10

Nathan Fellman


People also ask

How do you check a condition for all items in a list Python?

Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.

How do you check if a certain value is in a list?

Besides the Find and Replace function, you can use a formula to check if a value is in a list. Select a blank cell, here is C2, and type this formula =IF(ISNUMBER(MATCH(B2,A:A,0)),1,0) into it, and press Enter key to get the result, and if it displays 1, indicates the value is in the list, and if 0, that is not exist.

How do you check if something exists in Python?

How to check if a variable exists in Python. To check if a local variable exists in Python, use in operator and check inside the locals() dictionary. To check if a global variable exists in Python, use in operator and check inside the globals() dict. To check if an object has an attribute, use the hasattr() function.


2 Answers

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):
like image 246
Ken Avatar answered Oct 10 '22 20:10

Ken


Use any().

if any(t < 0 for t in x):
    # do something
like image 37
Daniel Pryden Avatar answered Oct 10 '22 20:10

Daniel Pryden