2

I was puzzled by seeing that python returns True for a comparison like this: 'A' == ('A')

then I found this explanation from this question.

Python compares every element in the tuple to the other term of comparison. My question is how can I avoid that? What I'm looking for is a '==' logical operator that returns True for 'A' == 'A' or ('A') == ('A') but false for 'A' ==' ('A').

Community
  • 1
  • 1
DaniPaniz
  • 1,058
  • 2
  • 13
  • 24
  • 2
    `('A')` is not a tuple, is it? `type(('A'))` returns `str`. – Psidom Nov 08 '16 at 14:13
  • Oh, my bad. I wasn't aware defining a single element tuple was a special case. – Jacob H Nov 08 '16 at 14:15
  • 3
    The comma defines a tuple, not the parentheses. The exception is the empty tuple `()`, which could (should?) have been written `(,)`, but `()` wasn't needed to represent any parenthesized expression. – chepner Nov 08 '16 at 14:15

2 Answers2

8

Your "explanation" has nothing to do with your actual problem.

('A') is not a tuple. It is simply a string. A single-element tuple is defined like this: ('A',). When you use an actual tuple, your comparison correctly returns False:

>>> 'A' == ('A',)
False
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

The right answer is already there provided by Daniel Roseman. Just an addition:

>>> type("A")
<type 'str'>

>>> type(("A"))
<type 'str'>

>>> type(("A",))
<type 'tuple'>
Community
  • 1
  • 1
dlask
  • 8,776
  • 1
  • 26
  • 30