Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does the extra comma at the end of a dict, list or set has any special meaning?

Tags:

I noticed by chance that adding an extra separator comma at the end of a list, dictionary or set is syntactically correct and does not seem to add anything to the data structure:

In [1]: d1 = {'a': 1, 'b': 2}  In [2]: d2 = {'c': 10, 'd': 20,}  In [3]: d1 Out[3]: {'a': 1, 'b': 2}  In [4]: d2 Out[4]: {'c': 10, 'd': 20} 

Does it have any special meaning or usage?
The only one I found is to explicit a data structure during an initialization:

In [14]: r = (1)  In [15]: r Out[15]: 1  In [16]: r = (1,)  In [17]: r Out[17]: (1,) 
like image 535
WoJ Avatar asked Mar 15 '15 17:03

WoJ


1 Answers

It has no special meaning in a list or dictionary, but can be useful when using source code change management tools, see below.

Non-empty tuples are defined by using a comma between elements, the parentheses are optional and only required in contexts where the comma could have a different meaning.

Because the comma defines the tuple, you need at least one comma if there is just the one element:

>>> 1 1 >>> 1, (1,) >>> type((1,)) # need parens to distinguish comma from the argument separator <type 'tuple'> 

The empty tuple is defined by using empty parentheses:

>>> type(()) <type 'tuple'> 

The trailing comma can be helpful in minimising how many lines changed when adding new lines; adding an additional line to a dictionary with a trailing comma would not change the last existing entry:

a_value = {     key1: value1,     key2: value2,     # inserting here doesn't require adding a comma     # to the preceding line. } 
like image 67
Martijn Pieters Avatar answered Oct 30 '22 21:10

Martijn Pieters