[] and {} vs list() and dict(), which is better?

我知道它们基本上都是一样的东西,但在风格方面,哪个更好(更多Pythonic),用来创建一个空的列表或字典?


In terms of speed, it's no competition for empty lists/dicts:

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077

and for non-empty:

>>> timeit("[1,2,3]")
0.24316302770330367
>>> timeit("list((1,2,3))")
0.44744206316727286
>>> timeit("list(foo)", setup="foo=(1,2,3)")
0.446036018543964
>>> timeit("{'a':1, 'b':2, 'c':3}")
0.20868602015059423
>>> timeit("dict(a=1, b=2, c=3)")
0.47635635255323905
>>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")
0.9028228448029267

Also, using the bracket notation let's you use list and dictionary comprehensions, which may be reason enough.


In my opinion [] and {} are the most pythonic and readable ways to create empty lists/dicts.

Be wary of set() 's though, for example:

this_set = {5}
some_other_set = {}

Can be confusing. The first creates a set with one element, the second creates an empty dict and not a set.


The dict literal might be a tiny bit faster as its bytecode is shorter:

In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()

In [4]: dis.dis(a)
  1           0 BUILD_MAP                0
              3 RETURN_VALUE

In [5]: dis.dis(b)
  1           0 LOAD_GLOBAL              0 (dict)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE

Same applies to the list vs []

链接地址: http://www.djcxy.com/p/31692.html

上一篇: 为什么有时可以用{}替换set()?

下一篇: []和{} vs list()和dict(),哪个更好?