Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list syntax explanation

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?

like image 317
Mitch Phillipson Avatar asked Nov 30 '22 06:11

Mitch Phillipson


2 Answers

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.

like image 199
Andrew Clark Avatar answered Dec 06 '22 10:12

Andrew Clark


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: ().)

like image 29
Vinod Kurup Avatar answered Dec 06 '22 10:12

Vinod Kurup