tags:

views:

192

answers:

4

Hi.

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.
+1  A: 

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)

Terence Honles
+9  A: 

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.

unutbu
Wow, thanks for the profiling. I had always wanted to know how it was done.
sukhbir
+1: worrying about this is completely wrong-headed.
S.Lott
`[]` is pronounced "empty list constant"; how does Alex pronounce `list()`? "result of calling list built-in with no args"???
John Machin
+8  A: 

list() is inherently slower than [], because

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

b) there is function invocation,

c) 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.

Nas Banov
+1: It feels good to understand why `list()` is slower than `[]`!
EOL
@EnTerr: Thanks for the explanation.
sukhbir
@EnTerr: In the case of `list()` it has only to check if there was any arg at all ... "check if iterable" and "create list with elements" just don't happen; they only apply if there is an arg. It's even possible that the C code for `[]` calls the same C code as `list()`. In any case the time involved in (c) would be tiny compared with (a) + (b).
John Machin
@John Machin - sorry for confusion, what i meant in (c) was that it will need to check if there was argument, yes. the rest was about what will happen if there were argument, which in our case there is none
Nas Banov
+1  A: 

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?
Georg