Last Updated: February 25, 2016
·
18.64K
· jairtrejo

Trailing comma in python data structures

When you are defining a data structure in Python, like a dictionary, a tuple, a list, etc.:

capitals = {
    'China': 'Beijing',
    'India': 'New Delhi',
    'Mexico': 'Mexico City',
}

You can leave a trailing comma on the last entry. It is useful because then every line has the same format and adding entries to the end is the same as adding them to the middle.

It also prevents the frequent bug of writing:

countries = [
    'China',
    'India'
]

And later adding 'Mexico':

countries = [
    'China',
    'India'
    'Mexico'
]

Which creates the list:

['China', 'IndiaMexico']

1 Response
Add your response

I usually use a slightly different syntax to prevent that bug, but it's bitten me in the past.

I use leading commas instead of trailing commas, a habit that I think I picked up from Haskell config files in Linux or something. It's served me well and continues to annoy my coworkers.

over 1 year ago ·