[Python-ideas] Faq 4.28 Suggestion -- Trailing comas

Leszek Dubiel leszek at dubiel.pl
Mon Mar 17 09:56:35 CET 2008

I would suggest to add question 4.28 to faq. Everybody who learns Python 
reads that and will not ask questions about "one-element tuples". I have 
compiled answer from responses to my last question about one-element tuple.

Question: Why python allows to put comma at the end of list? This looks 
ugly and seems to break common rules...

Answer: There are may reasons that follow.

1. If you defined multiline dictionary

        d = {       
            "A": [1, 5],
            "B": [6, 7],  # last trailing comma is optional but good style

it would be easier to add more elements, because you don't have to care 
about colons -- you always put colon at the end of line and don't have 
to reedit other lines. It eases sorting of such lines too -- just cut 
line and paste above.

2. Missing comma can lead to errors that are hard to diagnose. For example:

        x = [

contains tree elements "fee", "fiefoo" and "fum". So if programmer puts 
comma always at the end of line he saves lots of trouble in a future.

2. Nearly all reasonable programming languages (C, C++, Java) allow for an
extra trailing comma in a comma-delimited list, for consistency and to
make programmatic code generation easier. So for example [1,2,3,] is
intentionally correct.

3. Creating one-element tuples using tuple(['hello']) syntax is much much
slower (a factor of 20x here) then writing just ['hello', ].  Trailing 
when you only have one item are how python tuple syntax is defined
allowing them to use commas instead of needing other tokens. If python
didn't allow comma at the end of tuple, you will have to use such slow 

4. The same rule applies to other type of lists, where delimiter can occur
at the end. For example both strings "alfa\nbeta\n" and "alfa\nbeta" contain
two lines.


-- http://mail.python.org/pipermail/python-list/2003-October/231419.html
-- http://mail.python.org/pipermail/python-ideas/2008-March/001478.html
-- http://mail.python.org/pipermail/python-ideas/2008-March/001475.html

More information about the Python-ideas mailing list