6
votes

Possible Duplicate:
Creating a list in Python- something sneaky going on?
Creating an empty list in Python

Consider the following:

mylist = list()

and:

mylist = []

Is there any benefit to using list() or [] - should one be used over the other in certain situation?

2
I'm inclined to think the [] literal would be faster since it saves a function call, but I've been wrong before. Did you try measuring this? - Frédéric Hamidi
@FrédéricHamidi -- I'm pretty sure I've seen this in a SO post before. I'll try to find it ... - mgilson
I haven't tried measuring, I will try and update soon, thanks Frederic - Sherlock
@FrédéricHamidi: Isn't it just syntactic sugar? In that case it probably wouldn't save a function call. - David Robinson
This question is phrased better, in my opinion. - Marcin

2 Answers

19
votes

For an empty list, I'd recommend using []. This will be faster, since it avoids the name look-up for the built-in name list. The built-in name could also be overwritten by a global or local name; this would only affect list(), not [].

The list() built-in is useful to convert some other iterable to a list, though:

a = (1, 2, 3)
b = list(a)

For completeness, the timings for the two options for empty lists on my machine (Python 2.7.3rc2, Intel Core 2 Duo):

In [1]: %timeit []
10000000 loops, best of 3: 35 ns per loop

In [2]: %timeit list()
10000000 loops, best of 3: 145 ns per loop
4
votes

The two are completely equivalent, except that it is possible to redefine the identifier list to refer to a different object. Accordingly, it is safer to use [] unless you want to be able to redefine list to be a new type.

Technically, using [] will be very slightly faster, because it avoids name lookup. This is unlikely to be significant in any case, unless the programme is allocating lists constantly and furiously.

As Sven notes, list has other uses, but of course the question does not ask about those.