Skip to content

Instantly share code, notes, and snippets.

@reata
Created October 1, 2022 08:20
Show Gist options
  • Save reata/5d0fee871252031d44f025b9aeba0a0b to your computer and use it in GitHub Desktop.
Save reata/5d0fee871252031d44f025b9aeba0a0b to your computer and use it in GitHub Desktop.
在Python中用[]和list()创建列表有区别吗?
from ast import dump, parse
from dis import dis
from timeit import timeit, default_number
a = []
b = list()
print(f"a == b: {a == b}")
print(f"a is b: {a is b}")
# a == b: True
# a is b: False
print(f"Running a = [] {default_number} times take {timeit('a = []')} seconds")
print(f"Running b = list() {default_number} times take {timeit('b = list()')} seconds")
# Running a = [] 1000000 times take 0.015558651999981521 seconds
# Running b = list() 1000000 times take 0.07794420999971408 seconds
print(f"AST for a = []: f{dump(parse('a = []'))}")
print(f"AST for b = list(): f{dump(parse('b = list'))}")
print("\n")
# AST for a = []: fModule(body=[Assign(targets=[Name(id='a', ctx=Store())], value=List(elts=[], ctx=Load()))])
# AST for b = list(): fModule(body=[Assign(targets=[Name(id='b', ctx=Store())], value=Name(id='list', ctx=Load()))])
print(f"Bytecodes for a = []:")
dis("a = []")
print(f"Bytecodes for b = list:")
dis("b = list()")
# Bytecodes for a = []:
# 1 0 BUILD_LIST 0
# 2 STORE_NAME 0 (a)
# 4 LOAD_CONST 0 (None)
# 6 RETURN_VALUE
# Bytecodes for b = list:
# 1 0 LOAD_NAME 0 (list)
# 2 CALL_FUNCTION 0
# 4 STORE_NAME 1 (b)
# 6 LOAD_CONST 0 (None)
# 8 RETURN_VALUE
@reata
Copy link
Author

reata commented Oct 1, 2022

[]和list()都可以用来创建列表:

  1. 由a==b可知,两种方法创建的列表,是等值的。(但注意Python并不会为空列表创建常量,所以a和b是两个单独的对象,并不共享内存,a is b为False)
  2. 运行速度上,[]比list()要快3~4倍
  3. 从AST来看,二者的不同在于,同样是赋值,[]的值是List,list()的值是Name,代表变量。
  4. 从Bytecode来看,[]直接翻译为BUILD_LIST,而list()是LOAD_NAME + CALL_FUNCTION。

综合可知,list()创建列表,需要走变量求值的过程,依次在本地作用域(local),闭包作用域(enclosed),全局作用域(global),内建作用域(builtin)搜索变量list,然后调用该变量。没有在自己代码里覆盖list变量的情况下,list存在于内建作用域中。而[]快就快在跳过了这个流程。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment