Reputation: 1365
Suppose I have the following code:
target = 'abc1234y'
if ('x' and 'y') in target:
print('x and y are in target')
Why is if ('x' and 'y') in target
true?
Why doesn't this code produce error?
Why do braces have no effect?
This does not seem logical, since if ('x' and 'y') = true
then ('y' and 'x')
should also be true, however, this is no the case.
At the same time expression if ('y' and 'x') in target
is false
Upvotes: 0
Views: 343
Reputation: 7118
There are two things to consider here:
and
works with strings'x' and 'y'
is not True
.
'x' and 'y'
is 'y'
, which might seem confusing but it makes sense when looking at how and
and or
work in general:
a and b
returns b
if a is True
, else returns a
.a or b
returns a
if a is True
, else returns b
.Thus:
'x' and 'y'
is 'y'
'x' or 'y'
is 'x'
The brackets do have an effect in your if statement. in
has a higher precedence than and
meaning that if you write
if 'x' and 'y' in target:
it implicitly means the same as
if 'x' and ('y' in target):
which will only check if y is in the target string. So, using
if ('x' and 'y') in target:
will have an effect. You can see the whole table of operator precedences in the Python docs about Expressions.
To achieve what you are wanting to do, @Prem and @Olga have already given two good solutions:
if 'y' in target and 'x' in target:
or
if all(c in target for c in ['x','y']):
Upvotes: 4
Reputation: 31
You may want to use all
instead
if all(c in target for c in ['x','y']):...
Upvotes: 0
Reputation: 47
Because it is checking for just 'y' in target. You need something like this:
target = 'abc1234y'
if 'y' in target and 'x' in target:
print('x and y are in target')
Upvotes: 0
Reputation: 4044
You seem to be confusing how AND
operator works.
'x' and 'y'
Out[1]: 'y'
and
'y' and 'x'
Out[1]: 'x'
So in your first case, you do check if y
is present. In reverse, you check if x
is present in string.
Upvotes: 2