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:
This question is related to
python
performance
list
coding-style
timeit
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
t = [] # implicit instantiation
t = t.append(1)
in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.
t = t.append(2)
I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by
t = list() # explicit instantiation
then it works fine.
list()
is inherently slower than []
, because
there 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.
I use []
.
Just to highlight @Darkonaut answer because I think it should be more visible.
new_list = []
or new_list = list()
are both fine (ignoring performance), but append()
returns None
, as result you can't do new_list = new_list.append(something)
.
Source: Stackoverflow.com