[] and {} vs list() and dict(), which is better?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands
--
Chapters
00:00 [] And {} Vs List() And Dict(), Which Is Better?
00:17 Answer 1 Score 57
00:38 Accepted Answer Score 246
01:11 Answer 3 Score 6
01:22 Answer 4 Score 20
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/5790...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #performance #list #dictionary
#avk47
    Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands
--
Chapters
00:00 [] And {} Vs List() And Dict(), Which Is Better?
00:17 Answer 1 Score 57
00:38 Accepted Answer Score 246
01:11 Answer 3 Score 6
01:22 Answer 4 Score 20
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/5790...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #performance #list #dictionary
#avk47
ACCEPTED ANSWER
Score 246
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.
ANSWER 2
Score 57
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.
ANSWER 3
Score 20
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 []
ANSWER 4
Score 6
IMHO, using list() and dict() makes your Python look like C.  Ugh.