Why doesn't [[]] == list(list())

From the the Python 2 documentation on the list constructor

class list([iterable])

Return a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, [].

When you pass a list to list() it returns a copy, not a nested list, whereas [[]] creates an empty nested list - or rather a list containing a single element which is itself an empty list.


Note   -   This is notably absent from the corresponding Python 3 documentation, but it holds true for Python 3 regardless.


list does not construct a list that contains its argument; it constructs a list whose elements are contained in its argument. list([]) does not return [[]]; it returns []. Thus, list(list()) == list([]) == [].


list(...) constructor is not doing the same thing as the list literal [...]. The constructor takes any iterable and makes a list out of its items

>>> list((1, 2, 3))
[1, 2, 3]
>>> list("foo")
['f', 'o', 'o']
>>> list(list())

whereas a list literal defines a list with exactly the enumerated items

>>> [(1, 2, 3)]
[(1, 2, 3)]
>>> ["foo"]
['foo']
>>> [[]]
[[]]

Note that when called without any arguments, list() produces the same result as [].

Tags:

Python

List