What is the best way to create a new empty list in Python?
l = []
or
l = list()
I am asking this because of two reasons:
- Technical reasons, as to which is faster. (creating a class causes overhead?)
- Code readability - which one is the standard convention.
Here is how you can test which piece of code is faster:
However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.
Readability is very subjective. I prefer
[]
, but some very knowledgable people, like Alex Martelli, preferlist()
because it is pronounceable.I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code
in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.
I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by
then it works fine.
I use
[]
.list()
is inherently slower than[]
, becausethere is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.