Python list syntax explanation

I noticed that when I use python, I sometimes make a typographical error and have a definition that looks something like

L = [1,2,3,] 

My question is: why does this not cause an error?

+4
source share
5 answers

This does not cause an error, since it is an intentional function that allows commas for lists and tuples.

This is especially important for tuples, since otherwise it would be difficult to define one element:

 >>> (100,) # this is a tuple because of the trailing comma (100,) >>> (100) # this is just the value 100 100 

It can also simplify reordering or adding items to long lists.

+8
source

In Python docs:

The back comma is only required to create one tuple (aka a singleton); it is optional in all other cases. A single expression without a trailing comma does not create a tuple, but gives the value of this expression. (To create an empty tuple, use an empty pair of parentheses :().)

+4
source

My question is: why does this not cause an error?

The comma is ignored because it can be convenient:

 funcs = [ run, jump, # laugh ] 
+4
source

You can find out more about this in the official documentation:

Why does Python allow commas at the end of lists and tuples?

Python allows you to 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 do this.

When you have a literal value for a list, tuple or dictionary distributed over several lines, it is easier to add more elements because you do not need to remember to add a comma to the previous line. Lines can also be sorted in your editor without creating a syntax error.

Accidental lack of a comma can lead to errors that are difficult to diagnose. For instance:

 x = [ "fee", "fie" "foo", "fum" ] 

This list looks like four items, but in fact it contains three: "fee" , "fiefoo" and "fum" . Always adding a comma avoids this source of errors.

Providing a trailing comma can also facilitate the creation of program codes.

+3
source

Do it

 >>> l = 1,2,3, >>> l (1, 2, 3) 

() are optional. , means that you are creating a sequence.

Keep it

 >>> l = 1, >>> l (1,) >>> l = 1 >>> l 1 

Yet again. , means sequence. () are optional.

Don't think about

 [ 1, 2, 3, ] 

as a tuple 1, 2, 3, inside the list constructor [ ] . The list is created from the base tuple.

+1
source

Source: https://habr.com/ru/post/1397894/


All Articles