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

后端 未结 7 981
粉色の甜心
粉色の甜心 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 09:52

    Adding a couple of parentheses around the order in which actions are performed might help you understand the results better:

    # Build two element tuple comprising of 
    # (0, 0) == 0 result and 0
    >>> ((0, 0) == 0), 0
    (False, 0)
    
    # Build two element tuple comprising of
    # 0 and result of (0, 0) == 0 
    >>> 0, (0 == (0, 0))
    (0, False)
    
    # Create two tuples with elements (0, 0) 
    # and compare them
    >>> (0, 0) == (0, 0) 
    True
    

    The comma is used to to separate expressions (using parentheses we can force different behavior, of course). When viewing the snippets you listed, the comma , will separate it and define what expressions will get evaluated:

    (0, 0) == 0 ,   0
    #-----------|------
      expr 1      expr2
    

    The tuple (0, 0) can also be broken down in a similar way. The comma separates two expressions comprising of the literals 0.

提交回复
热议问题