Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mylist = list() vs mylist = [] in Python [duplicate]

Tags:

python

list

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?

like image 922
Sherlock Avatar asked Aug 02 '12 15:08

Sherlock


2 Answers

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
like image 148
Sven Marnach Avatar answered Sep 28 '22 09:09

Sven Marnach


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.

like image 26
Marcin Avatar answered Sep 28 '22 10:09

Marcin