简体   繁体   中英

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?

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

My question is, why doesn't this cause an error?

The trailing comma is ignored because it can be convenient:

funcs = [ run,
          jump,
          # laugh
        ]

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM