Python 3中list()和[ ]的区别

5
在Python 3中,使用list()[]初始化一个list是否有区别?

据我所知,它们是等价的。 - Ottotos
3
从技术角度来讲,一个是将对象转换为列表并返回的函数,另一个则是列表本身。有点类似于int(0)0。实际上它们之间没有区别。 - jfaccioni
4
我认为 [] 会更快,因为它不需要全局查找再调用函数。除此之外,它与原来的内容一样。 - bereal
1
将“list = int; list()”与“list = int; []”进行比较。 - chepner
5个回答

7

由于list()是一个返回列表对象的函数,而[]则是列表对象本身。第二种形式更快,因为它不涉及函数调用:

> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop

> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop

所以如果你真的想找出区别,那就是这样。但实际上它们是一样的。

这是编译级别的主要差异。感谢@jfaccioni,我点赞了这个评论。 - Avinash Dalvi
我在我的回答中添加了一个计时示例,其中list更快。我承认这是一个特殊情况... - hiro protagonist

4

它们几乎是等价的;构造函数变体执行函数查找和函数调用;而文字常量则不执行-反汇编Python字节码显示:

from dis import dis


def list_constructor():
    return list()

def list_literal():
    return []


print("constructor:")
dis(list_constructor)

print()

print("literal:")
dis(list_literal)

这将输出:
constructor:
  5           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

literal:
  8           0 BUILD_LIST               0
              2 RETURN_VALUE

关于时间问题:在这个答案中给出的基准可能会对某些情况(可能很少见)产生误导。例如,与此进行比较:
$ python3 -m timeit 'list(range(7))'
1000000 loops, best of 5: 224 nsec per loop
$ python3 -m timeit '[i for i in range(7)]'
1000000 loops, best of 5: 352 nsec per loop

使用 list 从生成器构建列表比使用列表推导式更快。我认为这是因为列表推导式中的 for 循环是 Python 循环,而在 Python 解释器中的 C 实现中,相同的循环在 list 版本中运行。


同时请注意,list 可以被重新赋值为其他变量(例如,list = int,现在 list() 将返回整数 0),但你不能修改 []

并且,虽然可能很显然,但为了完整起见:这两个版本具有不同的接口:list 接受一个可迭代对象作为参数。它将遍历它,并将元素放入新的列表中;字面量版本则不会(除了显式的列表推导式):

print([0, 1, 2])  # [0, 1, 2]
# print(list(0, 1,2))  # TypeError: list expected at most 1 argument, got 3

tpl = (0, 1, 2)
print([tpl])           # [(0, 1, 2)]
print(list(tpl))       # [0, 1, 2]

print([range(3)])      # [range(0, 3)]
print(list(range(3)))  # [0, 1, 2]

# list-comprehension
print([i for i in range(3)])      # [0, 1, 2]
print(list(i for i in range(3)))  # [0, 1, 2]  simpler: list(range(3))

2

这两种方式在功能上产生相同的结果,但是Python内部实现不同:

import dis


def brackets():
    return []


def list_builtin():
    return list()

print(dis.dis(brackets))
  5           0 BUILD_LIST               0
              2 RETURN_VALUE

print(dis.dis(list_builtin))
 9           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

1

让我们来看一个例子:

A = ("a","b","c")
B = list(A)
C = [A]

print("B=",B)
print("C=",C)

# list is mutable:
B.append("d")
C.append("d")

## New result
print("B=",B)
print("C=",C)

Result:
B= ['a', 'b', 'c']
C= [('a', 'b', 'c')]

B= ['a', 'b', 'c', 'd']
C= [('a', 'b', 'c'), 'd']

基于这个例子,我们可以说:[ ] 不会尝试将元组转换为元素列表,而 list() 是一种尝试将元组转换为元素列表的方法。

0

list() 方法接受序列类型并将它们转换为列表。这用于将给定的元组转换为列表。

sample_touple = ('a', 'C', 'J', 13)
list1 = list(sample_touple)
print ("List values ", list1)

string_value="sampletest"
list2 = list(string_value)
print ("List string values : ", list2)

输出:

List values  ['a', 'C', 'J', 13]                                                                                                                              
List string values :  ['s', 'a', 'm', 'p', 'l', 'e', 't', 'e', 's', 't']   

在编程中,如何使用[]直接声明为列表

sample = [1,2,3]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接