pythondata-structuressyntaxtuplestrailing

Does the extra comma at the end of a dictionary, list or set has any special meaning in Python?


I noticed by chance that adding an extra separator comma at the end of a list, dictionary or set is syntactically correct and does not seem to add anything to the data structure:

In [1]: d1 = {'a': 1, 'b': 2}

In [2]: d2 = {'c': 10, 'd': 20,}

In [3]: d1
Out[3]: {'a': 1, 'b': 2}

In [4]: d2
Out[4]: {'c': 10, 'd': 20}

Does it have any special meaning or usage?
The only one I found is to explicit a data structure during an initialization:

In [14]: r = (1)

In [15]: r
Out[15]: 1

In [16]: r = (1,)

In [17]: r
Out[17]: (1,)

Solution

  • (In a list or dictionary: it has no special meaning, but can be useful when using source code change management tools, see below).

    In a tuple: Non-empty tuples are defined by using a comma between elements, the parentheses are optional and only required in contexts where the comma could have a different meaning.

    Because the comma defines the tuple, you need at least one comma if there is just one element:

    >>> 1
    1
    >>> 1,
    (1,)
    >>> type((1,)) # need parens to distinguish comma from the argument separator
    <type 'tuple'>
    

    An empty tuple is defined by using empty parentheses:

    >>> type(())
    <type 'tuple'>
    

    The trailing comma can be helpful in minimising how many lines changed when adding new lines; adding an additional line to a dictionary with a trailing comma would not change the last existing entry:

    a_value = {
        key1: value1,
        key2: value2,
        # inserting here doesn't require adding a comma
        # to the preceding line.
    }