We know that,
a = 1
b = 2
print(not a > b)
is the correct way of using the "not" keyword and the below throws an error
a = 1
b = 2
print(a not > b)
since "not" inverts the output Boolean.
Thus, by this logic the correct way for checking the presence of a member in a list should be
a = 1
b = [2,3,4,5]
print(not a in b)
But I find the most common way is
a = 1
b = [2,3,4,5]
print(a not in b)
which from the logic given in previous example should throw an error.
So what is the correct way of using the "not in" operator in Python3.x?
CodePudding user response:
not in
is a special case that simplifies to exactly what you tried first. Namely,
a not in b
literally simplifies to not (a in b)
. It also works (slightly differently, but same idea) for is
.
a is not b`
is equivalent to not (a is b)
. Python added these because they flow naturally like English prose. On the other hand, a not < b
doesn't look or feel natural, so it's not allowed. The not in
and is not
are special cases in the grammar, not small parts of a general rule about where not
can go. The only general rule in play is that not
can always be used as a prefix operator (like in not (a < b)
)
CodePudding user response:
what is the correct way of using the "not in" operator
There is only one way to use the not in
operator. Your not a in b
instead uses the not
operator and the in
operator.
PEP 8 doesn't seem to have an opinion about which to use, but about the similar is not
operator (thanks Silvio) it says:
Use
is not
operator rather thannot ... is
. While both expressions are functionally identical, the former is more readable and preferred:# Correct: if foo is not None:
# Wrong: if not foo is None:
So I'd say not in
should also be preferred, for the same reason.
CodePudding user response:
not
, not in
and in
are all valid operators. Transitively, not (in_expression)
is also valid
Correct way? Refer Zen of Python.
CodePudding user response:
First of all not in
, is not a two separate operator, is constituently a single operator ,and also known as membership operator. There is another membership operator that is in
. Membership operator has high precedence than logical NOT
, AND
and OR
.
print(not a in b)
-> This is actually first evaluating a in b
then result is inverted by the logical 'not' and then result is printed.
So as per your example it should print True as a in b
gives False
then it is inverted to True
via logical NOT
operator.
print(a not in b)
-> Here python checks if a
is not a part of the b
, if it is return 'False' else 'True` .
So as per your example it should return True
as a is not a part of b.
I think a not in b
is more clear than not a in b
.I would suggest to use membership operator for testing the membership.
However the result will remain same for both kind of expression but the process of evaluating is completely different.