What's the idiomatic syntax for prepending to a short python list?

后端 未结 5 1622
清酒与你
清酒与你 2020-11-27 09:42

list.append() is the obvious choice for adding to the end of a list. Here\'s a reasonable explanation for the missing list.prepend(). Assuming my

5条回答
  •  时光取名叫无心
    2020-11-27 10:20

    If someone finds this question like me, here are my performance tests of proposed methods:

    Python 2.7.8
    
    In [1]: %timeit ([1]*1000000).insert(0, 0)
    100 loops, best of 3: 4.62 ms per loop
    
    In [2]: %timeit ([1]*1000000)[0:0] = [0]
    100 loops, best of 3: 4.55 ms per loop
    
    In [3]: %timeit [0] + [1]*1000000
    100 loops, best of 3: 8.04 ms per loop
    

    As you can see, insert and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert is more common option and I, personally prefer this way to prepend to list.

提交回复
热议问题