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']
Written by Jair Trejo
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Related Tags
#python
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#