Reputation: 293
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?
Upvotes: 4
Views: 313
Reputation: 55956
You can read more about in the official documentation:
Why does Python allow commas at the end of lists and tuples?
Python lets you add a trailing comma at the end of lists, tuples, and dictionaries:
[1, 2, 3,]
('a', 'b', 'c',)
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}
There are several reasons to allow this.
When you have a literal value for a list, tuple, or dictionary spread across multiple lines, it’s easier to add more elements because you don’t have to remember to add a comma to the previous line. The lines can also be sorted in your editor without creating a syntax error.
Accidentally omitting the comma can lead to errors that are hard to diagnose. For example:
x = [
"fee",
"fie"
"foo",
"fum"
]
This list looks like it has four elements, but it actually contains three: "fee"
, "fiefoo"
and "fum"
. Always adding the comma avoids this source of error.
Allowing the trailing comma may also make programmatic code generation easier.
Upvotes: 3
Reputation: 107608
My question is, why doesn't this cause an error?
The trailing comma is ignored because it can be convenient:
funcs = [ run,
jump,
# laugh
]
Upvotes: 4
Reputation: 2776
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: ().)
Upvotes: 4
Reputation: 208475
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.
Upvotes: 8
Reputation: 391854
Do this
>>> l = 1,2,3,
>>> l
(1, 2, 3)
The ()
's are optional. The ,
, means that you're creating a sequence.
Observe this
>>> l = 1,
>>> l
(1,)
>>> l = 1
>>> l
1
Again. The ,
means it's a sequence. The ()
are optional.
It's not wrong to think of
[ 1, 2, 3, ]
as a tuple 1, 2, 3,
inside a list constructor [ ]
. A list is created from the underlying tuple.
Upvotes: 1