03-12-2020, 02:02 PM
Python List append() vs extend()
A profound understanding of Python lists is fundamental to your Python education. Today, I wondered: what’s the difference between two of the most-frequently used list methods: vs. ?
I shot a small video explaining the difference and which method is faster—you can play it as you read over this tutorial:
Here’s the short answer — vs :
The difference between and is that the former adds only one element and the latter adds a collection of elements to the list.
You can see this in the following example:
In the code, you first add integer elements 1 and 2 to the list using two calls to the method. (If you need a deeper understanding, check out my detailed article about the append() method on this blog.)
Then, you use the extend method to add the three elements 3, 4, and 5 in a single call of the method.
[b]Which Method is Faster — extend() or append()?[/b]
To answer this question, I’ve written a short script that tests the runtime performance of creating large lists of increasing sizes using the and the methods.
My thesis is that the method should be faster for larger list sizes because Python can append elements to a list in a batch rather than by calling the same method again and again.
I used my notebook with an Intel® Core i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM.
Then, I created 100 lists with both methods, extend() and append(), with sizes ranging from 10,000 elements to 1,000,000 elements. As elements, I simply incremented integer numbers by one starting from 0.
Here’s the code I used to measure and plot the results: which method is faster—append() or extend()?
The code consists of three high-level parts:
Here’s the resulting plot that compares the runtime of the two methods append() vs extend(). On the x axis, you can see the list size from 0 to 1,000,000 elements. On the y axis, you can see the runtime in seconds needed to execute the respective functions.
![[Image: append_vs_extend-1.jpg]](https://blog.finxter.com/wp-content/uploads/2020/03/append_vs_extend-1.jpg)
The resulting plot shows that both methods are extremely fast for a few tens of thousands of elements. In fact, they are so fast that the function of the time module cannot capture the elapsed time.
But as you increase the size of the lists to hundreds of thousands of elements, the method starts to win:
For large lists with one million elements, the runtime of the method is 60% faster than the runtime of the method.
The reason is the already mentioned batching of individual append operations.
However, the effect only plays out for very large lists. For small lists, you can choose either method. Well, for clarity of your code, it would still make sense to prefer over if you need to add a bunch of elements rather than only a single element.
Your Coding Skills – What’s the Next Level?
If you love coding and you want to do this full-time from the comfort of your own home, you’re in luck:
I’ve created a free webinar that shows you how I started as a Python freelancer after my computer science studies working from home (and seeing my kids grow up) while earning a full-time income working only part-time hours.
Webinar: How to Become Six-Figure Python Freelancer?
Join 21,419 ambitious Python coders. It’s fun!![[Image: 1f604.png]](https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f604.png)
A profound understanding of Python lists is fundamental to your Python education. Today, I wondered: what’s the difference between two of the most-frequently used list methods:
Code:
append()Code:
extend()I shot a small video explaining the difference and which method is faster—you can play it as you read over this tutorial:
Here’s the short answer —
Code:
append()Code:
extend()- The method adds elementCode:
list.append(x)to the end of theCode:x.Code:list
- The method adds all elements inCode:
list.extend(iter)to the end of theCode:iter.Code:list
The difference between
Code:
append()Code:
extend()You can see this in the following example:
Code:
>>> l = []
>>> l.append(1)
>>> l.append(2)
>>> l
[1, 2]
>>> l.extend([3, 4, 5])
>>> l
[1, 2, 3, 4, 5]In the code, you first add integer elements 1 and 2 to the list using two calls to the
Code:
append()Then, you use the extend method to add the three elements 3, 4, and 5 in a single call of the
Code:
extend()[b]Which Method is Faster — extend() or append()?[/b]
To answer this question, I’ve written a short script that tests the runtime performance of creating large lists of increasing sizes using the
Code:
extend()Code:
append()My thesis is that the
Code:
extend()I used my notebook with an Intel® Core i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM.
Then, I created 100 lists with both methods, extend() and append(), with sizes ranging from 10,000 elements to 1,000,000 elements. As elements, I simply incremented integer numbers by one starting from 0.
Here’s the code I used to measure and plot the results: which method is faster—append() or extend()?
Code:
import time def list_by_append(n): '''Creates a list & appends n elements''' lst = [] for i in range(n): lst.append(n) return lst def list_by_extend(n): '''Creates a list & extends it with n elements''' lst = [] lst.extend(range(n)) return lst # Compare runtime of both methods
list_sizes = [i * 10000 for i in range(100)]
append_runtimes = []
extend_runtimes = [] for size in list_sizes: # Get time stamps time_0 = time.time() list_by_append(size) time_1 = time.time() list_by_extend(size) time_2 = time.time() # Calculate runtimes append_runtimes.append((size, time_1 - time_0)) extend_runtimes.append((size, time_2 - time_1)) # Plot everything
import matplotlib.pyplot as plt
import numpy as np append_runtimes = np.array(append_runtimes)
extend_runtimes = np.array(extend_runtimes) print(append_runtimes)
print(extend_runtimes) plt.plot(append_runtimes[:,0], append_runtimes[:,1], label='append()')
plt.plot(extend_runtimes[:,0], extend_runtimes[:,1], label='extend()') plt.xlabel('list size')
plt.ylabel('runtime (seconds)') plt.legend()
plt.savefig('append_vs_extend.jpg')
plt.show()The code consists of three high-level parts:
- In the first part, you define two functions andCode:
list_by_append(n)that take as input argument an integer list sizeCode:list_by_extend(n)and create lists of successively increasing integer elements using theCode:nandCode:append()methods, respectively.Code:extend()
- In the second part, you compare the runtime of both functions using 100 different values for the list size .Code:
n
- In the third part of, you plot everything using the Python matplotlib library.
Here’s the resulting plot that compares the runtime of the two methods append() vs extend(). On the x axis, you can see the list size from 0 to 1,000,000 elements. On the y axis, you can see the runtime in seconds needed to execute the respective functions.
![[Image: append_vs_extend-1.jpg]](https://blog.finxter.com/wp-content/uploads/2020/03/append_vs_extend-1.jpg)
The resulting plot shows that both methods are extremely fast for a few tens of thousands of elements. In fact, they are so fast that the
Code:
time()But as you increase the size of the lists to hundreds of thousands of elements, the
Code:
extend()For large lists with one million elements, the runtime of the
Code:
extend()Code:
append()The reason is the already mentioned batching of individual append operations.
However, the effect only plays out for very large lists. For small lists, you can choose either method. Well, for clarity of your code, it would still make sense to prefer
Code:
extend()Code:
append()Your Coding Skills – What’s the Next Level?
If you love coding and you want to do this full-time from the comfort of your own home, you’re in luck:
I’ve created a free webinar that shows you how I started as a Python freelancer after my computer science studies working from home (and seeing my kids grow up) while earning a full-time income working only part-time hours.
Webinar: How to Become Six-Figure Python Freelancer?
Join 21,419 ambitious Python coders. It’s fun!
![[Image: 1f604.png]](https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f604.png)

