-
-
Save reata/5d0fee871252031d44f025b9aeba0a0b to your computer and use it in GitHub Desktop.
在Python中用[]和list()创建列表有区别吗?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[]和list()都可以用来创建列表:
综合可知,list()创建列表,需要走变量求值的过程,依次在本地作用域(local),闭包作用域(enclosed),全局作用域(global),内建作用域(builtin)搜索变量list,然后调用该变量。没有在自己代码里覆盖list变量的情况下,list存在于内建作用域中。而[]快就快在跳过了这个流程。