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?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With