在Python中,为什么list(None)是一个错误,但[None]不是一个错误? [英] In Python, why is list(None) an error but [None] is not?
问题描述
将None
传递给Python的list
构造函数是TypeError
:
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
但是使用方括号来实例化list
是可以的;将None
与内置函数一起使用也可以:
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]
我的理解是list()
和[]
是创建新list
的等效方法.我想念什么?
My understanding was that list()
and []
were equivalent ways of creating a new list
. What am I missing?
推荐答案
它们与不等价. list()
尝试遍历其参数,使每个对象成为一个单独的列表项,而列表文字[]
恰好采用它给出的内容.比较:
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']
您无法遍历None
,因此会出现错误.使用任何不可迭代的参数,您将得到相同的结果:
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
要使用list()
获得a = [None]
的等价物,您必须将其传递给单个对象,例如,
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!
这篇关于在Python中,为什么list(None)是一个错误,但[None]不是一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!