Creating an empty list in Python

前端 未结 5 1393
长情又很酷
长情又很酷 2020-11-28 17:17

What is the best way to create a new empty list in Python?

l = [] 

or

l = list()

I am asking this because

相关标签:
5条回答
  • 2020-11-28 17:53

    I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code

    t = [] # implicit instantiation
    t = t.append(1)
    

    in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.

    t = t.append(2)
    

    I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by

    t = list() # explicit instantiation
    

    then it works fine.

    0 讨论(0)
  • 2020-11-28 17:55

    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?
    0 讨论(0)
  • 2020-11-28 18:05

    list() is inherently slower than [], because

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

    2. there is function invocation,

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

    0 讨论(0)
  • 2020-11-28 18:09

    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.

    0 讨论(0)
  • 2020-11-28 18:11

    Just to highlight @Darkonaut answer because I think it should be more visible.

    new_list = [] or new_list = list() are both fine (ignoring performance), but append() returns None, as result you can't do new_list = new_list.append(something).

    0 讨论(0)
提交回复
热议问题