In Python, why is there an error in the list (No) but [No] not?

Passing None to the Python list constructor is a TypeError :

 >>> l = list(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable 

But using parentheses to instantiate a list is fine; using None with built-in features is also great:

 >>> l = [None] >>> l.append(None) >>> l [None, None] 

I realized that list() and [] are equivalent ways to create a new list . What am I missing?

+6
source share
4 answers

They are not equivalent. list() tries to iterate over its argument, making each object a separate list item, while the literal list [] just accepts exactly what it gave. For comparison:

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

You cannot iterate over None , hence the error. You will get the same with any indestructible argument:

 >>> list(1) Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> list(1) TypeError: 'int' object is not iterable 

To get the equivalent of a = [None] using list() , you need to pass it iterable with a single object, for example,

 a = list([None]) 

although this will create a list literal and then copy it, so this is not very useful in this trivial example!

+21
source

When you do [None] , you create a new list with one item that is None . To use the list constructor, you can copy such a list as follows:

 list([None]) 
Constructor

list takes iterations (an object over which it can iterate), rather than individual items.

+1
source

Because, as the trace said, list expects iterability (list, tuple, etc.), and None is not alone. For example, this will work:

 list([None]) list((1, 2, 3)) 

This will fail:

 list(None) list(1, 2, 3) 
+1
source

Just because [None] not an empty list, since it contains None !

 >>> len([None]) 1 >>> len(None) TypeError: object of type 'NoneType' has no len() >>> len([]) 0 
0
source

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


All Articles