8

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?

Community
  • 1
  • 1
Sherlock
  • 5,557
  • 6
  • 50
  • 78

2 Answers2

22

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
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • What about explicit > implicit? When I see "list()" I don't bat an eye. If I see "[]" I think twice, especially when I found out that python is introducing {} for both dict() and set() :o – gsk Aug 02 '12 at 15:16
  • 4
    @gsk: A list with two elements `[1, 2]`; a list with one element: `[1]`; a list without elements `[]`. Seems pretty explicit to me. I know the same example would look different for sets in Python 3 – this is about the only design decision for 3.x I don't like. – Sven Marnach Aug 02 '12 at 15:17
  • 1
    @gsk and I think twice when list() is called without parameters. [] is more explicit to me, and kind of is by definition... since that is the definition. – Logan Aug 02 '12 at 15:23
  • Ok Ok :D don't gang up on me. I too once preferred [] to list(), but since then my tastes have changed. If I had only commented several months ago, I might've fallen into friendlier company. [] it is – gsk Aug 02 '12 at 15:28
5

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.

Marcin
  • 48,559
  • 18
  • 128
  • 201