What makes Pythons add a list method quickly?

I am comparing various ways to add items to a list in python. I tested on my computer, and the results, of course, will differ on other computers.

Option 1 : 5.80 seconds in total 50,000 items!

a = []
for i in range(50000):
    a = a + [i]

Option 2 : 2.27 seconds 10,000,000 items

a = []
for i in range(10000000):
    a += [i]

Option 3 : 1.53 seconds 10,000,000 items

a = []
for i in range(10000000):
    a.append(i)

Not surprisingly, option 1 is slow because it creates a new copy of the list each time.

Option 2 is much faster using the extended assignment operator. It modifies the original list in place.

But option 3 is still significantly faster. I expected that using the append () method and the extended assignment operator would have the same results.

append() , + =?

PS: python:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

taskinoor [i] . . , . , , , append(), . , .

4: 1,91 10 000 000 ( 2)

a = []
b = [0]
for i in range(10000000):
    b[0] = i
    a += b
+4
1

[i]. :

>>> import dis
>>> def func_2(a, i):
...     a += [i]
... 
>>> def func_3(a, i):
...     a.append(i)
... 
>>> dis.dis(func_2)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (i)
              6 BUILD_LIST               1
              9 INPLACE_ADD         
             10 STORE_FAST               0 (a)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        
>>> dis.dis(func_3)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_ATTR                0 (append)
              6 LOAD_FAST                1 (i)
              9 CALL_FUNCTION            1
             12 POP_TOP             
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        
>>> 

6 BUILD_LIST, - . , 3.

+3

Source: https://habr.com/ru/post/1658532/


All Articles