You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
In Python, the list is similar to an array that is a data structure that is an ordered sequence of defined elements within the square brackets. In this, we will see what an empty list is and how to declare it in Python. In python, an empty list is defined as the list with no elements or items on the list.
To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.
Here is how you can test which piece of code is faster:
% python -mtimeit "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop
% python -mtimeit "l=list()"
1000000 loops, best of 3: 0.297 usec per loop
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, prefer list()
because it is pronounceable.
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 []
.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With