What is the syntax rule for having trailing commas in tuple definitions?

前端 未结 10 1602
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:54

In the case of a single element tuple, the trailing comma is required.

a = (\'foo\',)

What about a tuple with multiple elements? It seems t

10条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 06:28

    It is only required for single-item tuples to disambiguate defining a tuple or an expression surrounded by parentheses.

    (1)  # the number 1 (the parentheses are wrapping the expression `1`)
    (1,) # a 1-tuple holding a number 1
    

    For more than one item, it is no longer necessary since it is perfectly clear it is a tuple. However, the trailing comma is allowed to make defining them using multiple lines easier. You could add to the end or rearrange items without breaking the syntax because you left out a comma on accident.

    e.g.,

    someBigTuple = (
                       0,
                       1,
                       2,
                       3,
                       4,
                       5,
                       6,
                       7,
                       8,
                       9,
                       10,
                       #...
                       10000000000,
                   )
    

    Note that this applies to other collections (e.g., lists and dictionaries) too and not just tuples.

提交回复
热议问题