3

I just checked the difference of speed between list() and [], and was surprised to see that list() was 3 times slower than [] for list creation. I tested this in ipython with %timeit magic.

In [1]: %timeit a=list()
10000000 loops, best of 3: 67.5 ns per loop
In [2]: %timeit b=[]
10000000 loops, best of 3: 21.9 ns per loop

Then I thought maybe something is not happening until we actually put an element into it, so I tested the following.

In [3]: %timeit list().append(1)
10000000 loops, best of 3: 143 ns per loop

In [4]: %timeit [].append(1)
10000000 loops, best of 3: 88.7 ns per loop

Now the relationship changed, so then I tested only the appends.

In[5]: a=list()
In[6]: b=[]
In [7]: %timeit a.append(1)
10000000 loops, best of 3: 49.8 ns per loop
In [8]: %timeit b.append(1)
10000000 loops, best of 3: 54.2 ns per loop

What kind of sorcery is this? Why aren't the lists and the appends equivalent?

diogoaos
  • 400
  • 1
  • 14
  • I have found this: http://stackoverflow.com/a/2736723/2235928 – XNor Apr 19 '16 at 08:39
  • That's an interesting answer. And from this [this answer](http://stackoverflow.com/a/2736725/2904853), we know that the two call different things. I'm open to the possibility that the call function on list() alone accounts for the increased run time, but what about the appends? They're both objects of type list, so it should take roughly the same time. – diogoaos Apr 19 '16 at 09:12

0 Answers0