'Does the extra comma at the end of a dictionary, list or set has any special meaning in Python?
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,)
Solution 1:[1]
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.
}
Solution 2:[2]
It’s useful for consistency across multiple lines:
d1 = {
'a': 1,
'b': 2,
}
You can rearrange or add lines without changing commas. It doesn’t change anything about the information represented.
Solution 3:[3]
You can use dis module to verify that behaviour of both objects is exactly the same.
In [10]: import dis
In [11]: def make_dict():
return {"a": 1, "b": 2}
....:
In [12]: def make_dict_2():
return {"a": 1, "b": 2,}
....:
In [13]: dis.dis(make_dict)
2 0 BUILD_MAP 2
3 LOAD_CONST 1 (1)
6 LOAD_CONST 2 ('a')
9 STORE_MAP
10 LOAD_CONST 3 (2)
13 LOAD_CONST 4 ('b')
16 STORE_MAP
17 RETURN_VALUE
In [14]: dis.dis(make_dict_2)
2 0 BUILD_MAP 2
3 LOAD_CONST 1 (1)
6 LOAD_CONST 2 ('a')
9 STORE_MAP
10 LOAD_CONST 3 (2)
13 LOAD_CONST 4 ('b')
16 STORE_MAP
17 RETURN_VALUE
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martijn Pieters |
| Solution 2 | Ry- |
| Solution 3 | Akavall |
