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