0

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

Abdulrahman Bres
  • 2,375
  • 1
  • 18
  • 36
0rt
  • 1,295
  • 1
  • 17
  • 25

4 Answers4

4

There are two things to consider here:

How 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'

What the parentheses do

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.

Solution

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']):
Kilian Batzner
  • 5,978
  • 4
  • 36
  • 47
2

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.

Spandan Brahmbhatt
  • 3,276
  • 5
  • 20
  • 33
0

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')
Prem
  • 47
  • 7
0

You may want to use all instead if all(c in target for c in ['x','y']):...

Olga
  • 21
  • 7