extra empty element when removing an element from a tuple

前端 未结 2 798
一个人的身影
一个人的身影 2021-01-15 03:12

I have a question about the following python outcome. Suppose I have a tuple :

a = ( (1,1), (2,2), (3,3) )

I want to remove (2,2)

2条回答
  •  生来不讨喜
    2021-01-15 04:06

    Python uses a trailing comma in case a tuple has only one element:

    In [21]: type((1,))
    Out[21]: tuple
    

    from the docs:

    A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

    >>> empty = ()
    >>> singleton = 'hello',    # <-- note trailing comma
    >>> len(empty)
    0
    >>> len(singleton)
    1
    >>> singleton
    ('hello',)
    

提交回复
热议问题