Why is a tuple of tuples of length 1 not actually a tuple unless I add a comma?

前端 未结 3 1632
故里飘歌
故里飘歌 2021-01-22 23:14

Given a tuple of tuples T:

((\'a\', \'b\'))

and an individual tuple t1:

(\'a\',\'b\')
         


        
3条回答
  •  没有蜡笔的小新
    2021-01-22 23:35

    The problem is because T is not a tuple of tuples, it is just a tuple. The comma makes a tuple, not the parentheses. Should be:

    >>> T = (('a','b'),)
    >>> t1 = ('a', 'b')
    >>> t1 in T
    True
    

    In fact, you can loose the outer parentheses:

    >>> T = ('a','b'),
    >>> t1 = 'a','b'
    >>> type(T)
    
    >>> type(T[0])
    
    >>> type(t1)
    
    >>> t1 in T
    True
    

    Although sometimes they are needed for precedence, if in doubt put them in. But remember, it is the comma that makes it a tuple.

提交回复
热议问题