Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why is list(None) an error but [None] is not?

Tags:

python

list

Passing None to Python's 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 brackets to instantiate a list is fine; using None with the built-in functions is also fine:

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

My understanding was that list() and [] were equivalent ways of creating a new list. What am I missing?

like image 950
jds Avatar asked Jun 09 '14 12:06

jds


2 Answers

They are not equivalent. list() attempts to iterate over its argument, making each object a separate list item, whereas a list literal [] just takes exactly what it's given. Compare:

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

You can't iterate over None, hence the error. You will get the same with any non-iterable 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 would have to pass it an iterable with a single object in, e.g.

a = list([None])

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

like image 194
jonrsharpe Avatar answered Oct 24 '22 09:10

jonrsharpe


When you do [None] you are creating a new list, with one element, which is None. To use list constructor you can copy such a list like this:

list([None])

list constructor accepts iterables (object over which it can iterate), not single elements.

like image 44
BartoszKP Avatar answered Oct 24 '22 09:10

BartoszKP