mylist = list()与mylist = []在Python中 [英] mylist = list() vs mylist = [] in Python
问题描述
Possible Duplicate:
Creating a list in Python- something sneaky going on?
Creating an empty list in Python
请考虑以下内容:
mylist = list()
和:
mylist = []
使用list()
或[]
是否有任何好处-在某些情况下应优先使用另一个?
Is there any benefit to using list()
or []
- should one be used over the other in certain situation?
推荐答案
对于空列表,建议使用[]
.这将更快,因为它避免了对内置名称list
的名称查找.内置名称也可以用全局或本地名称覆盖;这只会影响list()
,而不会影响[]
.
For an empty list, I'd recommend using []
. This will be faster, since it avoids the name look-up for the built-in name list
. The built-in name could also be overwritten by a global or local name; this would only affect list()
, not []
.
内置的list()
对于将其他可迭代对象转换为列表很有用,
The list()
built-in is useful to convert some other iterable to a list, though:
a = (1, 2, 3)
b = list(a)
为完整起见,我的机器上空列表的两个选项(Python 2.7.3rc2,Intel Core 2 Duo)的计时:
For completeness, the timings for the two options for empty lists on my machine (Python 2.7.3rc2, Intel Core 2 Duo):
In [1]: %timeit []
10000000 loops, best of 3: 35 ns per loop
In [2]: %timeit list()
10000000 loops, best of 3: 145 ns per loop
这篇关于mylist = list()与mylist = []在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!