Why are trailing commas allowed in a list?
list, python, syntax
Solution
The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.
Changing:
s = ['manny',
'mo',
'jack',
]
to:
s = ['manny',
'mo',
'jack',
'roger',
]
involves only a one-line change in the diff:
s = ['manny',
'mo',
'jack',
+ 'roger',
]
This beats the more confusing multi-line diff when the trailing comma was omitted:
s = ['manny',
'mo',
- 'jack'
+ 'jack',
+ 'roger'
]
The latter diff makes it harder to see that only one line was added and that the other line didn't change content.
It also reduces the risk of doing this:
s = ['manny',
'mo',
'jack'
'roger' # Added this line, but forgot to add a comma on the previous line
]
and triggering implicit string literal concatenation, producing `s = ['manny', 'mo', 'jackroger']` instead of the intended result.
Problem
I am curious why in Python a trailing comma in a list is valid syntax, and it seems that Python simply ignores it: ``` >>> ['a','b',] ['a', 'b'] ``` It makes sense when its a tuple since `('a')` and `('a',)` are two different things, but in lists?