181

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?

2

5 Answers 5

305
+50

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.

11
  • 11
    This makes the (most) sense, but I would really be surprised if the parser of the language was designed to make diffs easier. Jul 22, 2012 at 6:00
  • 123
    @BurhanKhalid: Language designers are programmers, and programmers do many things to make their lives easier. Jul 22, 2012 at 6:14
  • 10
    @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|)"]".
    – Voo
    Jul 22, 2012 at 12:41
  • 25
    This 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. Mar 26, 2013 at 20:05
  • 11
    @Voo I thought the same too but the latter grammar has to be defined anyway because it's still a valid Python list. Dec 27, 2015 at 10:55
42

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.

39

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.

3
  • 1
    This is neat, but you can avoid this by pre-pending the comma. I do that all the time when writing SQL Jul 22, 2012 at 5:21
  • 45
    Even if you prepend the comma to each element, you still have to omit the comma on the first one. Jul 22, 2012 at 5:25
  • A linter should be able to catch this, no? Apr 9, 2016 at 19:37
6

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')

4
  • ('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. Jul 22, 2012 at 5:58
  • 1
    They're silently discarded in both cases, it's just that in a tuple it's needed to differentiate it from a string in bracket.
    – richo
    Jul 22, 2012 at 17:03
  • tuple('a') is probably a bad example, because in general tuple(x) and (x,) are not the same thing. tuple('ab') != ('ab',). tuple('a') == ('a',) only because 'a' is a string of length 1.
    – chepner
    May 31, 2018 at 17:19
  • From the REPL: >>> ("a",) == ("a") False >>> ("ab",) == ("ab") False >>> ("ab", "bc",) == ("ab", "bc") True
    – Seraphya
    Jan 29, 2020 at 22:53
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.