extra empty element when removing an element from a tuple

前端 未结 2 799
一个人的身影
一个人的身影 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 03:57

    It indicates a one-element tuple, just to prevent confusion.

    (1,) is a tuple, while (1) is just the number 1 with unnecessary parentheses.

    0 讨论(0)
  • 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',)
    
    0 讨论(0)
提交回复
热议问题