Home » Python » Creating an empty list in Python

Creating an empty list in Python

Posted by: admin November 1, 2017 Leave a comment

Questions:

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:

  1. Technical reasons, as to which is faster. (creating a class causes overhead?)
  2. Code readability – which one is the standard convention.
Answers:

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.

Questions:
Answers:

list() is inherently slower than [], because

  1. there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),

  2. there is function invocation,

  3. 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.

Questions:
Answers:

I use [].

  1. It’s faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?
Questions:
Answers:

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 = [];
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();

then it works fine.

Questions:
Answers:

I would write [] …though I can’t give any details about the speed (I doubt it would make a difference other than the function doesn’t have to figure out if it’s been handed a generator or another iterable object)

Questions:
Answers:

I would be careful about the context…

l=[]

is NOT creating a list! [] is a list created ahead of time, and the instruction above is only creating a reference to it. And it is NOT a constant, it’s a mutable object. For example if you do

def f(l=[]):
    ...

you will discover you are not creating list every time you call f, but you’ve rather created a “static” variable l. The right way to do it is

def(l=list()):
    ...

The correct way to create a list is list().