178

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284

5 Answers5

302

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 10
    This makes the (most) sense, but I would really be surprised if the parser of the language was designed to make diffs easier. – Burhan Khalid Jul 22 '12 at 06:00
  • 118
    @BurhanKhalid: Language designers are programmers, and programmers do many things to make their lives easier. – Greg Hewgill Jul 22 '12 at 06:14
  • 4
    @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. – Raymond Hettinger Jul 22 '12 at 06:15
  • 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 '12 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. – Adam Rosenfield Mar 26 '13 at 20:05
  • …besides, I would usually forget to add the comma. Are there any compelling reasons _not_ to have it there? – Micah Walter Aug 27 '14 at 18:38
  • 10
    @Voo I thought the same too but the latter grammar has to be defined anyway because it's still a valid Python list. – Alexander Suraphel Dec 27 '15 at 10:55
  • 4
    I think the `s = [` should be on its own line as well, in case the `'manny'` element needs to be changed. – Will Sheppard Mar 20 '18 at 11:25
  • Are there compelling reasons to use commas at all? Why disallow whitespace separation? – Josh Cooley Sep 07 '19 at 18:00
  • What is meant by `diff`, is this an abbreviation for `difference` or some fancy python-term I'm unaware of? – Andreas L. Jan 18 '21 at 16:50
  • @AndreasL. I realize it's a bit late, but it means the [Unix utility](https://en.wikipedia.org/wiki/Diff) – Tomeamis Apr 01 '21 at 09:07
40

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Óscar López
  • 232,561
  • 37
  • 312
  • 386
37

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.

Keith
  • 42,110
  • 11
  • 57
  • 76
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')

richo
  • 8,717
  • 3
  • 29
  • 47
  • `('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 Jul 22 '12 at 05: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 '12 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 '18 at 17:19
  • From the REPL: `>>> ("a",) == ("a") `False `>>> ("ab",) == ("ab") `False `>>> ("ab", "bc",) == ("ab", "bc") `True – Seraphya Jan 29 '20 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.

Nitish Chauhan
  • 375
  • 4
  • 7