In the case of a single element tuple, the trailing comma is required.
a = ('foo',)
What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?
a = ('foo1', 'foo2')
b = ('foo1', 'foo2',)
Coding style is your taste, If you think coding standard matters there is a PEP-8 That can guide you.
What do you think of the result of following expression?
Yep, x is just an number.
Also, consider the situation where you want:
So in this case the outer parentheses are nothing more than grouping parentheses. To make them tuple you need to add a trailing comma. i.e.
In all cases except the empty tuple the comma is the important thing. Parentheses are only required when required for other syntactic reasons: to distinguish a tuple from a set of function arguments, operator precedence, or to allow line breaks.
The trailing comma for tuples, lists, or function arguments is good style especially when you have a long initialisation that is split over multiple lines. If you always include a trailing comma then you won't add another line to the end expecting to add another element and instead just creating a valid expression:
Assuming that started as a 2 element list that was later extended it has gone wrong in a perhaps not immediately obvious way. Always include the trailing comma and you avoid that trap.
Another advantage of trailing commas is that it makes diffs look nicer. If you started with
and changed it to
The diff would look like
Whereas if you had started with a trailing comma, like
Then the diff would just be
PEP 8 -- Style Guide for Python Code - When to Use Trailing Commas
Trailing commas are usually optional, except they are mandatory when making a tuple of one element (and in Python 2 they have semantics for the print statement). For clarity, it is recommended to surround the latter in (technically redundant) parentheses.
Yes:
OK, but confusing:
When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples).
Yes:
No:
It's optional: see the Python wiki.
Summary: single-element tuples need a trailing comma, but it's optional for multiple-element tuples.