0

The code

for item in ('sin', 'cos', 'sinc', 'sin^2'):
    print(item not in ('sin^2'))

produces the result

False
True
True
False

but

for item in ('sin', 'cos', 'sinc', 'sin^2'):
    print(item not in ['sin^2'])

produces the result

True
True
True
False

Why?

  • 3
    You don't have a tuple in the first one. You just have a string. – Daniel Roseman Apr 17 '19 at 21:07
  • 2
    `('sin^2')` is not a tuple, that is a string. The *comma* makes the tuple, not the parentheses. Note, `my_tuple = 1,2` is a valid tuple, so is `my_tuple = 3,` and `my_tuple = (3,)`, whereas `my_tuple = (3)` is an `int` – juanpa.arrivillaga Apr 17 '19 at 21:09

1 Answers1

1

The expression is being treated as a parenthesized string rather than a tuple. So it ends up being a substring match. To define it as a single-element tuple, there must be a trailing comma:

print(item not in ('sin^2',))

This is described here: https://wiki.python.org/moin/TupleSyntax

jspcal
  • 50,847
  • 7
  • 72
  • 76