Python has a built-in any() function for exactly “if any” purpose.
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):
if any Python example
Simple example code check if one of the following items is in a list.
a = [1, 2, 3, 4]
b = [2, 7]
if any(x in a for x in b):
print("a have any value of b:", True)
Output:
1 line without list comprehensions.
>>> any(map(lambda each: each in [2,3,4], [1,2]))
True
>>> any(map(lambda each: each in [2,3,4], [1,5]))
False
>>> any(map(lambda each: each in [2,3,4], [2,4]))
True
Using any() and all() to check if a list contains one set of values or another
all
and any
are functions that take some iterable and return True
, if
- in the case of
all
, no values in the iterable are falsy; - in the case of
any
, at least one value is truth.
if any(x==playerOne for x in board) or any(x==playerTwo for x in board):
# or
if playerOne in board or playerTwo in board:
if all(x == playerOne or x == playerTwo for x in board):
Comment if you have any doubts or suggestions on this Python if statement topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.