I understand that they are both
essentially the same thing, but in terms of style, which is the better (more Pythonic)
one to use to create an empty list or dict?
Sunday 24 December 2017
python - [] and {} vs list() and dict(), which is better?
itemprop="text">
class="post-text" itemprop="text"> class="normal">Answer
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 lets you use list and dictionary comprehensions, which may be
reason enough.
Subscribe to:
Post Comments (Atom)
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
-
I am new to dask and I found so nice to have a module that makes it easy to get parallelization. I am working on a project where I was able ...
No comments:
Post a Comment