Get which or-condition is met in an if-statement in Python
I have the following Python if-statement:
if element1 in list[2] or element2 in list[2] or 3 in list[2]:
do some more if-statements...
else:
print something...
Is it possible to print (or get in some way) which of the or-conditions are met (if there are any)? Because there are other if-statements in the if-clause, I don't want to use three different if-statements, which would be one solution. But this will end up in nearly 12 different if-statement. I just want to log which condition is met for further analysis. I googled of course, but found nothing so for. Thanks in advance.
Edit: Use case: try to implement a search algorithm with "AND" and "OR" function. I'm sure could be written much better and cleaner but for now counts what works ;-)
You can assign the boolean values to names:
a = element1 in list[2]
b = element2 in list[2]
c = 3 in list[2]
if a or b or c:
print(f"{element1} {'in' if a else 'not in'} list[2]")
print(f"{element2} {'in' if b else 'not in'} list[2]")
print(f"3 {'in' if c else 'not in'} list[2]")
This removes any benefits of short-circuiting though, since all the expressions need to be evaluated.
In python 3.8+ you can use assignment expressions:
if (a := (element1 in list[2])) or \
(b := (element2 in list[2])) or \
(c := (3 in list[2])):
try:
print(f"{element1} {'in' if a else 'not in'} list[2]")
print(f"{element2} {'in' if b else 'not in'} list[2]")
print(f"3 {'in' if c else 'not in'} list[2]")
except NameError:
pass
Keep in mind that this approach has the opposite problem: some names may not have been assigned because of short circuiting. You won't know the result for any name past the first false one.
Another way, if you really have a lot of conditions, is to build a list instead of naming each individual one:
test = [element1, element2, 3]
x = [t in list[2] for t in test]
if any(x):
for t, r in zip(test, x):
print(f"{t} {'in' if r else 'not in'} list[2]")
You can even go so far as to use sets:
test = {element1, element2, 3}
s2 = set(list[2])
x = test & s2
if x:
print('{x!r} in list[2]')
if y := test - x:
print('{y} not in list[2]')
The choice depends on your specific use-case.
If you wanted cleaner code then I would suggest putting the if statement checks inside a function and using a logger to log the truth of the statement.
import logging
def elem_in_list(elem, list):
if elem in list[2]:
logging.info(f"{elem} is in list")
return True
logging.info(f"{elem} is not in list")
return False
if elem_in_list(element1, list) or elem_in_list(element2, list) or elem_in_list(element3, list):
# do more if statements
else:
print(something)
This is perhaps a cleaner way of doing it, but you cannot get around using a load of if statements for comparisons as far as I know.