- python create a list with one more comma
- python create a tuple with one more comma
The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.
It’s a common syntactical convention to allow trailing commas in an array, languages like C and Java allow it, and Python seems to have adopted this convention for its list data structure. It’s particularly useful when generating code for populating a list: just generate a sequence of elements and commas, no need to consider the last one as an special case that doesn’t have a comma at the end.
Zero Element Tuples
In Python, zero-element tuples look like:
In this form, unlike the other tuple forms, parentheses are the essential elements, not commas.
One Element Tuples
One-element tuples look like:
The essential element here is the trailing comma. As for any expression, parentheses are optional, so you may also write one-element tuples like
but it is the comma, not the parentheses, that define the tuple.
Multiple Element Tuples
In Python, multiple-element tuples look like:
The essential elements are the commas between each element of the tuple. Multiple-element tuples may be written with a trailing comma, e.g.
but the trailing comma is completely optional. Just like all other expressions in Python, multiple-element tuples may be enclosed in parentheses, e.g.
but again, it is the commas, not the parentheses, that define the tuple.