Questions about list-creation

Terry Reedy tjreedy at udel.edu
Mon Nov 30 18:21:09 EST 2009


Manuel Graune wrote:
> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing.

Untrue. List() and [] happen to both evaluate to the same thing, an 
empty list. But there is no reason to expect list(<sometext>) and 
[<sometext>] to always evaluate to the same thing. The docs for list() 
calls and [] displays and comprehensions are quite different.

In particular, they clearly say that [x] interprets x as an item and 
creates a list with one item, x, while list(x) interprets x as an 
iterable, and creates a list with multiple items, the items of x. So. in 
particular, list([]) != [[]].

> For example "help([])" and "help(list())" point
> to the same documentation.

This has nothing to do with list(text) and [text]. [] evaluates to an 
instance that has no doc string, so help backs up to its class. Compare

 >>> help(1)
Help on int object:
...

The alternative to to print nothing, which would not be very helpful.

Try

 >>> help()
...
help> topics

and you will see that there is a topic LISTLITERALS, though not one for 
comprehensions or sets or even generators. The list of topics seems not 
to have been kept up to date.

Terry Jan Reedy




More information about the Python-list mailing list