Why in Python does “0, 0 == (0, 0)” equal “(0, False)”?

后端 未结 7 987
粉色の甜心
粉色の甜心 2020-12-04 09:20

In Python (I checked only with Python 3.6 but I believe it should hold for many of the previous versions as well):

(0, 0) == 0, 0   # results in a two elemen         


        
7条回答
  •  囚心锁ツ
    2020-12-04 10:09

    Another way to explain the problem: You're probably familiar with dictionary literals

    { "a": 1, "b": 2, "c": 3 }
    

    and array literals

    [ "a", "b", "c" ]
    

    and tuple literals

    ( 1, 2, 3 )
    

    but what you don't realize is that, unlike dictionary and array literals, the parentheses you usually see around a tuple literal are not part of the literal syntax. The literal syntax for tuples is just a sequence of expressions separated by commas:

    1, 2, 3
    

    (an "exprlist" in the language of the formal grammar for Python).

    Now, what do you expect the array literal

    [ 0, 0 == (0, 0) ]
    

    to evaluate to? That probably looks a lot more like it should be the same as

    [ 0, (0 == (0, 0)) ]
    

    which of course evaluates to [0, False]. Similarly, with an explicitly parenthesized tuple literal

    ( 0, 0 == (0, 0) )
    

    it's not surprising to get (0, False). But the parentheses are optional;

    0, 0 == (0, 0)
    

    is the same thing. And that's why you get (0, False).


    If you're wondering why the parentheses around a tuple literal are optional, it is largely because it would be annoying to have to write destructuring assignments that way:

    (a, b) = (c, d) # meh
    a, b = c, d     # better
    

提交回复
热议问题