2

In python2:

>>> 'a' in ('ab')
True
>>> 'a' in ('ab', 'c')
False

If I just want to test whether certain string exists in given tuple, looks like I cannot use 'in' operator when the tuple size is 1? Is there a consistent way to do this?

updated:

Thanks everyone. Tried this:

>>> tup='ab',
>>> type(tup)
<type 'tuple'>
>>> 'a' in tup
False

and it explains comma makes a tuple well.

Karata
  • 1,079
  • 8
  • 16
  • And by the way, try `'a' in ('ab', 'c')[0]` or `['a' in i for i in ('ab', 'c')]`. – Remi Guan Oct 30 '15 at 00:59
  • Since you are already doing this from the interactive interpreter, you could simply remove the `'a' in ` from both statements and see the generated output for yourself. – metatoaster Oct 30 '15 at 00:59

1 Answers1

9

Because ('ab') is not actually a tuple but a string.

The , is really what defines a tuple, not the parentheses (except for the empty tuple () as @chepner pointed out).

Try the same operation on ('ab',) and see what happens!

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • That's cool answer. Looks like parentheses are misleading cause "type(())" results in tuple type. – Karata Oct 30 '15 at 01:04
  • 3
    The empty tuple is the exception. `()` (no comma) defines an empty tuple; `(x,)` is a singleton, `(x,y)` is a 2-tuple, `(x,y,z)` is a 3-tuple, etc. – chepner Oct 30 '15 at 01:08