2023年 5月 28日

python a=[] 和 a=list() 的不同

初始化列表时,自己习惯用:

a=[]
  • 1

刷题时经常看到

a=list()
  • 1

从时间上对比了一下:

import time
sta=time.time()
for i in range(10000000):
    a=[]
print(time.time()-sta)
sta=time.time()
for i in range(10000000):
    a=list()
print(time.time()-sta)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
0.6291182041168213
1.4444737434387207
  • 1
  • 2

a=[]稍微快一些。

使用a=list()其实是调用了list类的__init__()方法,即:

    def __init__(self, seq=()): # known special case of list.__init__
        """
        Built-in mutable sequence.
        
        If no argument is given, the constructor creates a new empty list.
        The argument must be an iterable if specified.
        # (copied from class doc)
        """
        pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

所以用list()传入的需要是可迭代的对象。即:

a=[1,2,3,4]
b=[a]
c=list(a)
  • 1
  • 2
  • 3
b:[[1,2,3,4]]
c:[1,2,3,4]
  • 1
  • 2