import time
n = 100000
start_time = time.time()
l = []
for i in range(n):
l = l + [i * 2]
print('l = l + [...]: ', time.time() - start_time)
start_time = time.time()
l = []
for i in range(n):
l += [i * 2]
print('l += [...]: ', time.time() - start_time)
start_time = time.time()
l = []
for i in range(n):
l.append(i * 2)
print('l.append(...): ', time.time() - start_time)
l = l + [...]: 42.01468086242676
l += [...]: 0.021297931671142578
l.append(...): 0.01938176155090332
We can see that the "+"
operator is about 2167 slower than the append method.
The explanation is easy:
If we use the append method, we will simply append a further element to the list in each loop pass. Now we come to the first loop, in which we use l = l + [i * 2]
. The list will be copied in every loop pass. The new element will be added to the copy of the list and result will be reassigned to the variable l
. After this the old list will have to be removed by Python, because it is not referenced anymore. We can also see that the version with the augmented assignment ("+=")
, the loop in the middle, is only slightly slower than the version using "append"
.