Why are trailing commas allowed in a list?
Solution 1
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.
Solution 2
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 a special case that shouldn't have a comma at the end.
Solution 3
It helps to eliminate a certain kind of bug. It's sometimes clearer to write lists on multiple lines. But in, later maintenace you may want to rearrange the items.
l1 = [
1,
2,
3,
4,
5
]
# Now you want to rearrange
l1 = [
1,
2,
3,
5
4,
]
# Now you have an error
But if you allow trailing commas, and use them, you can easily rearrange the lines without introducing an error.
Solution 4
A tuple is different because ('a')
is expanded using implicit continuation and ()
s as a precendence operator, whereas ('a',)
refers to a length 1 tuple.
Your original example would have been tuple('a')
Solution 5
The main reason is to make diff less complicated. For example you have a list :
list = [
'a',
'b',
'c'
]
and you want to add another element to it. Then you will be end up doing this:
list = [
'a',
'b',
'c',
'd'
]
thus, diff will show that two lines have been changed, first adding ',' in line with 'c' and adding 'd' at last line.
So, python allows trailing ',' in last element of list, to prevent extra diff which can cause confusion.
Related videos on Youtube
Burhan Khalid
I work in banking; but my real love is aviation. I am also an active member of the Google Developer's Group Kuwait and StartupQ8, a community to help startups in Kuwait. I am always #SOreadytohelp When I am not busy in SO, I am busy plane spotting, planning my next Python workshop, working on my photography skills or trying to schedule time on a Boeing simulator. Some of my must-read threads on SO: Why is processing a sorted array faster than an unsorted array? What is the single most influential book every programmer should read? Hidden features of Python Strangest language feature
Updated on January 31, 2020Comments
-
Burhan Khalid over 4 years
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?-
Ciro Santilli OurBigBook.com over 8 years
-
Nayuki almost 7 yearsA trailing comma is also allowed in lists in C, C++, Java, JavaScript, etc.
-
-
Burhan Khalid almost 12 yearsThis is neat, but you can avoid this by pre-pending the comma. I do that all the time when writing SQL
-
Greg Hewgill almost 12 yearsEven if you prepend the comma to each element, you still have to omit the comma on the first one.
-
Burhan Khalid almost 12 years
('a'),
is a string; but my point was that trailing commas in tuples are significant, but in lists they don't appear to be yet Python accepts them. -
Burhan Khalid almost 12 yearsThis makes the (most) sense, but I would really be surprised if the parser of the language was designed to make diffs easier.
-
Greg Hewgill almost 12 years@BurhanKhalid: Language designers are programmers, and programmers do many things to make their lives easier.
-
Raymond Hettinger almost 12 years@BurhanKhalid Not so much to make things easier for the diff program; rather, the goal is to make it easier for humans to make and review edits.
-
Voo almost 12 years@Burhan If you don't believe that explanation, how about that it's also simpler to define the grammar that way? ;) Compare
List = "[" {Item ","} "]".
vs.List = "[" ({Item","}Item|)"]".
-
richo almost 12 yearsThey're silently discarded in both cases, it's just that in a tuple it's needed to differentiate it from a string in bracket.
-
Adam Rosenfield over 11 yearsThis also makes it easier for other programs to autogenerate code -- it's much easier to just print
"\"item\","
for each item than it is to print"\"item\""
for each item followed by","
for all but the last item. -
Micah Walter almost 10 years…besides, I would usually forget to add the comma. Are there any compelling reasons not to have it there?
-
Alexander Suraphel over 8 years@Voo I thought the same too but the latter grammar has to be defined anyway because it's still a valid Python list.
-
viki.omega9 about 8 yearsA linter should be able to catch this, no?
-
Will Sheppard over 6 yearsI think the
s = [
should be on its own line as well, in case the'manny'
element needs to be changed. -
chepner about 6 years
tuple('a')
is probably a bad example, because in generaltuple(x)
and(x,)
are not the same thing.tuple('ab') != ('ab',)
.tuple('a') == ('a',)
only because'a'
is a string of length 1. -
Josh Cooley almost 5 yearsAre there compelling reasons to use commas at all? Why disallow whitespace separation?
-
Seraphya over 4 yearsFrom the REPL:
>>> ("a",) == ("a")
False>>> ("ab",) == ("ab")
False>>> ("ab", "bc",) == ("ab", "bc")
True -
Abhimanyu Shekhawat almost 4 yearsThis answer is really beautiful.
-
Andreas L. over 3 yearsWhat is meant by
diff
, is this an abbreviation fordifference
or some fancy python-term I'm unaware of? -
Tomeamis about 3 years@AndreasL. I realize it's a bit late, but it means the Unix utility