Reputation: 113
I am using ____contains__ method in python as per below:
Case 1: True
if ('A','B','D').__contains__('A'or'E'):
print(True)
else:
print(False)
Case 2: False
if ('A','B','D').__contains__('E'or'B'):
print(True)
else:
print(False)
If I replace or with and, that works and also using expressions such as (('E' and 'A') and ('B' and 'C')) works.
Please could you confirm why or does not work in standard way like if I were to do something like if (B or C) condition? Also is there other ways of doing the above using regular expressions or lamda expressions?
Upvotes: 0
Views: 767
Reputation: 1413
First of all, don't use __contains__
like that. Use in
like this.
if ('A' or 'E') in ('A', 'B', 'C'):
pass
Hopefully this will start to show where your problem is. The a or b
is evaluating before the __contains__
is being called and only one of the values is being tested for inclusion.
The statement ('A' or 'E')
will simplify to 'A'
. That is why your first case is printing True
.
if ('E' or 'B') in ('A', 'B', 'C'):
pass
For your second case ('E' or 'B')
will evaluate to 'E'
, which isn't in ('A', 'B', 'C')
, so your second case prints False
.
Addendum
To correct this code you should be thinking a little bit more verbosely.
values = ('A', 'B', 'C')
if 'A' in values or 'E' in values:
pass
if 'E' in values or 'B' in values:
pass
Upvotes: 0
Reputation: 4305
You are using and and or incorrectly.
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. // https://docs.python.org/3/reference/expressions.html#boolean-operations
Also, double underscore functions are marked with the double underscore especially as a marker that people shouldn't usually use them.
(One of the) correct ways to write the above is:
my_tuple=('A','B','D')
if 'A' in my_tuple or 'E' in my_tuple:
print(True)
else:
print(False)
Upvotes: 1