[Tut] Python List append() Method - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python List append() Method (/thread-93942.html) |
[Tut] Python List append() Method - xSicKxBot - 03-09-2020 Python List append() Method <div><p>How can you add more elements to a given list? Use the <code>append()</code> method in Python. This tutorial shows you everything you need to know to help you master an essential method of the most fundamental container data type in the Python programming language.</p> <h2>Definition and Usage</h2> <p>The <code>list.append(x)</code> method—as the name suggests—appends element <code>x</code> to the end of the <code>list</code>. </p> <p>Here’s a short example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> l = [] >>> l.append(42) >>> l [42] >>> l.append(21) >>> l [42, 21]</pre> <p>In the first line of the example, you create the list <code>l</code>. You then append the integer element <code>42</code> to the end of the list. The result is the list with one element <code>[42]</code>. Finally, you append the integer element <code>21</code> to the end of that list which results in the list with two elements <code>[42, 21]</code>. </p> <h2>Syntax</h2> <p>You can call this method on each list object in Python. Here’s the syntax:</p> <p><code>list.append(element)</code></p> <h2>Arguments</h2> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th>Argument</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>element</code></td> <td>The object you want to append to the list.</td> </tr> </tbody> </table> </figure> <h2>Code Puzzle</h2> <p>Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Puzzle nums = [1, 2, 3] nums.append(nums[:]) print(len(nums)) # What's the output of this code snippet?</pre> <p>You can check out the solution on the <a rel="noreferrer noopener" href="https://app.finxter.com/learn/computer/science/509" target="_blank">Finxter app</a>. (I know it’s tricky!)</p> <h2>Examples</h2> <p>Let’s dive into a few more examples:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [2, 3] >>> lst.append(3) >>> lst.append([1,2]) >>> lst.append((3,4)) >>> lst [2, 3, 3, [1, 2], (3, 4)]</pre> <p>You can see that the <code>append()</code> method also allows for other objects. But be careful: you cannot append multiple elements in one method call. This will only add one new element (even if this new element is a list by itself). Instead, to add multiple elements to your list, you need to call the <code>append()</code> method multiple times.</p> <h2>Python List append() At The Beginning</h2> <p>What if you want to use the append() method at the beginning: you want to “append” an element just before the first element of the list. </p> <p>Well, you should work on your terminology for starters. But if you insist, you can use the <code>insert()</code> method instead. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 2, 3] >>> lst.insert(0, 99) >>> lst [99, 1, 2, 3]</pre> <p>The <code>insert(i, x)</code> method inserts an element <code>x</code> at position <code>i</code> in the list. This way, you can insert an element to each position in the list—even at the first position. Note that if you insert an element at the first position, each subsequent element will be moved by one position. In other words, element <code>i</code> will move to position <code>i+1</code>. </p> <h2>Python List append() Multiple or All Elements</h2> <p>But what if you want to append not one but multiple elements? Or even all elements of a given iterable. Can you do it with <code>append()</code>? Well, let’s try:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> l = [1, 2, 3] >>> l.append([4, 5, 6]) >>> l [1, 2, 3, [4, 5, 6]]</pre> <p>The answer is no—you cannot append multiple elements to a list <em>by using the <code>append()</code> method</em>. But you can use another method: the <code>extend()</code> method:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> l = [1, 2, 3] >>> l.extend([1, 2, 3]) >>> l [1, 2, 3, 1, 2, 3]</pre> <p>You call the <code>extend()</code> method on a list object. It takes an iterable as an input argument. Then, it adds all elements of the iterable to the list, in the order of their occurrence.</p> <h2>Python List append() vs extend()</h2> <p>I shot a small video explaining the difference and which method is faster, too:</p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="Python List append() vs extend() - Semantic and Speed Difference" width="1400" height="788" src="https://www.youtube.com/embed/VGg8sNJ9kOM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>The method <code>list.append(x)</code> adds element <code>x</code> to the end of the <code>list</code>. </p> <p>The method <code>list.extend(iter)</code> adds all elements in <code>iter</code> to the end of the <code>list</code>.</p> <p><strong>The difference between <code>append()</code> and <code>extend()</code> is that the former adds only one element and the latter adds a collection of elements to the list.</strong></p> <p>You can see this in the following example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> l = [] >>> l.append(1) >>> l.append(2) >>> l [1, 2] >>> l.extend([3, 4, 5]) >>> l [1, 2, 3, 4, 5]</pre> <p>In the code, you first add integer elements 1 and 2 to the list using two calls to the <code>append()</code> method. Then, you use the extend method to add the three elements 3, 4, and 5 in a single call of the <code>extend()</code> method.</p> <h3><strong>Which method is faster — extend() vs append()?</strong></h3> <p>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> and the <code>append()</code> methods. </p> <p>Our thesis is that the <code>extend()</code> 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.</p> <p>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. </p> <p>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.</p> <p>Here’s the code I used to measure and plot the results: which method is faster—append() or extend()?</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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()</pre> <p>The code consists of three high-level parts:</p> <ul> <li>In the first part of the code, you define two functions <code>list_by_append(n)</code> and <code>list_by_extend(n)</code> that take as input argument an integer list size <code>n</code> and create lists of successively increasing integer elements using the <code>append()</code> and <code>extend()</code> methods, respectively.</li> <li>In the second part of the code, you compare the runtime of both functions using 100 different values for the list size <code>n</code>. </li> <li>In the third part of the code, you plot everything using the Python <a rel="noreferrer noopener" href="https://blog.finxter.com/matplotlib-line-plot/" target="_blank">matplotlib library</a>.</li> </ul> <p>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.</p> <figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/append_vs_extend-2.jpg" alt="" class="wp-image-6633" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/append_vs_extend-2.jpg 640w, https://blog.finxter.com/wp-content/uploads/2020/03/append_vs_extend-2-300x225.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure> <p>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()</code> function of the <a rel="noreferrer noopener" href="https://docs.python.org/2/library/time.html#time.time" target="_blank">time module</a> cannot capture the elapsed time.</p> <p>But as you increase the size of the lists to hundreds of thousands of elements, the <code>extend()</code> method starts to win:</p> <p><strong>For large lists with one million elements, the runtime of the <code>extend()</code> method is 60% faster than the runtime of the <code>append()</code> method.</strong></p> <p>The reason is the already mentioned batching of individual append operations. </p> <p>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> over <code>append()</code> if you need to add a bunch of elements rather than only a single element. </p> <h2>Python List append() vs insert()</h2> </p> <h2>Python List append() vs concatenate()</h2> <h2>Python List append() If Not Exists</h2> <h2>Python List append() Return New List</h2> <h2>Python List append() Time Complexity, Memory, and Efficiency</h2> <h2>Python List append() at Index</h2> <h2>Python List append() Error</h2> <h2>Python List append() Empty Element</h2> <h2>Python List append() Thread Safe</h2> <h2>Python List append() Sorted</h2> <h2>Python List append() Dictionary</h2> <h2>Python List append() For Loop One Line</h2> </div> https://www.sickgaming.net/blog/2020/03/08/python-list-append-method/ |