The difference between “+” and append() in Python, and test their running speed with code.

Time:2020-11-24

In fact, if there is no obvious difference between the two in terms of memory usage, it should not be very easy to understand.

Let’s look at “+”, which means adding elements to the list. Strictly speaking, “+” does not really add elements to the list, but creates a new list, and copies the elements of the original list and the elements to be added into the memory space of the new list in turn. Will change the address in the list memory.

The append() method adds elements to the original list without changing the first address in the memory of the list.

Next, I’ll test the speed of the two additions with code:

import time
 
 result = []
 start = time.time()
 for i in range(10000):
     result = result + [i]
 print(len(result), ",", time.time() - start)
 
 result = []
 start = time.time()
 for i in range(10000):
     result.append(i)
 print(len(result), ",", time.time() - start)

Operation results:

From the running results, the addition speed using append() is faster than “+”.