Reputation: 73
I know we can check a variable against multiple conditions as
if all(x >= 2 for x in (A, B, C, D)):
print A, B, C, D
My question is , can we do the reverse? can we check one or two variables against same conditions(one or two)
null_check = (None,'','None')
if variable1 not in null_check and variable2 not in null_check:
print (variable1, variable2)
can we rewrite the above code as
if variable1 and variable2 not in null_check:
print (variable1, variable2)
If yes, which one is a better practice ?
Thanks in advance :)
Upvotes: 0
Views: 82
Reputation: 107347
No you can't do that, but as a pythonic approach you can put your null_check
items in a set
. And check the intersection:
null_check = {None,'','None'}
if null_check.intersection({var1, var2}): # instead of `or` or `any()` function
# pass
if len(null_check.intersection({var1, var2})) == 2: # instead of `and` or `all()` function
# pass
Upvotes: 1
Reputation: 49330
You can do this very similarly to your first code block:
null_check = (None,'','None')
if all(variable not in null_check for variable in (variable1, variable2)):
print (variable1, variable2)
Or:
null_check = (None,'','None')
variables = variable1, variable2 # defined elsewhere
if all(variable not in null_check for variable in variables:
print (*variables)
Upvotes: 1
Reputation: 117981
You can put the variables in a list
or tuple
, then use the same idea using all
to check that none of them are in your tuple
.
if all(var not in null_check for var in (variable1, variable2)):
print (variable1, variable2)
Upvotes: 3