+ 1

Comma after the last element of a list

In Python course, the topic lists state: "Most of the time, a comma won't follow the last item in a list. However, it is perfectly valid to place one there, and it is encouraged in some cases." when and why they encourage the use of comma after the last element?

12th Apr 2017, 4:55 AM
Denis Felipe
Denis Felipe - avatar
2 Answers
+ 2
It is actually a good question. If you leave a trailing comma at the end of list or tuple or dictionary, then it will be easier for you to modify it later on if you need to add any extra data. It makes multi-line lists easier to edit. However, there is a catch. It will work with strings but not with int or float. For example, try it yourself by running these. L1=[ 'J', 'A', 'C' 'K' ] L2 = [ 1, 2, 3 4 ] L1 will run but L2 will give SyntaxError. I guess it's better to work with .append or even better .insert. Using insert, you can put a value at any position.
12th Apr 2017, 6:00 AM
Tamoghna Saha
+ 2
Honestly, I never use trailing commas in lists. It doesn't make a difference for lists. monolist = [42] type(monolist) == list # True The situation is different for tuples! failtuple = (1) type(failtuple) == tuple # False # Here, failtuple is an int For a tuple with one element, the trailing comma is crucial! monotuple = (1,) type(monotuple) == tuple # True :-)
12th Apr 2017, 4:51 PM
Klaus-Dieter Warzecha
Klaus-Dieter Warzecha - avatar