I've noticed that when I'm using python, I'll occasionally make a typographical error and have a definition that looks something like
L = [1,2,3,]
My question is, why doesn't this cause an error?
It doesn't cause an error because it is an intentional feature that trailing commas are allowed for lists and tuples.
This is especially important for tuples, because otherwise it would be difficult to define a single element tuple:
>>> (100,) # this is a tuple because of the trailing comma
(100,)
>>> (100) # this is just the value 100
100
It can also make it easier to reorder or add elements to long lists.
From the Python docs:
The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With