Sick Gaming
[Tut] Python List insert() 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 insert() Method (/thread-94046.html)



[Tut] Python List insert() Method - xSicKxBot - 03-15-2020

Python List insert() Method

<div><p>How can you insert an element at a given index in a given list? Python’s <code>insert()</code> method is your friend. </p>
<p>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><strong>The <code>list.insert(i, element)</code> method adds an element <code>element</code> to an existing <code>list</code> at position <code>i</code>. All elements <code>j>i</code> will be moved by one index position to the right.</strong></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="">>>> lst = [1, 2, 3, 4]
>>> lst.insert(3, 99)
>>> lst
[1, 2, 3, 99, 4]</pre>
<p>In the first line of the example, you create the list <code>lst</code>. You then insert the integer element 99 at position 3 of the list. The result is the list with five elements <code>[1, 2, 3, 99, 4]</code>.</p>
<p>Try it yourself:</p>
<p> <iframe height="600px" width="100%" src="https://repl.it/repls/CoarseLeanIntroductory?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<h2>Syntax</h2>
<p>You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.insert(index, 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>index</code></td>
<td>Integer value representing the position <em>before </em>you want to insert an element</td>
</tr>
<tr>
<td><code>element</code></td>
<td>Object you want to insert into the list.</td>
</tr>
</tbody>
</table>
</figure>
<h2>Video</h2>
<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
# Puzzle created by Finxter Lee
lst = [1, 3, 4, 5, 6, 7, 8]
lst.insert(1, 2)
print(lst)
# 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/472" target="_blank">Finxter app</a>.</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 = [1, 2, 3]
>>> lst.insert(0, 99)
>>> lst
[99, 1, 2, 3]
>>> lst.insert(-1, 42)
>>> lst
[99, 1, 2, 42, 3]
>>> lst.insert(100, 0)
>>> lst
[99, 1, 2, 42, 3, 0]</pre>
<p>An interesting case is the second one where you use a negative index in the insert() method:</p>
<h2>Python List insert() Negative Index</h2>
<p>You can use a negative index in the <code>lst.insert(index, element)</code> method. With a negative index you count backwards, starting from the right. In other words, the index <code>-1</code> stands for the rightmost element in the list. The <code>insert()</code> method inserts the element right in front of the index position. Thus, you get the following behavior where the element is inserted to the second last position:</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 = ["Ann", "Bob", "Alice"]
>>> lst.insert(-1, "Liz")
>>> lst
['Ann', 'Bob', 'Liz', 'Alice']</pre>
<p>What happens if you count further, i.e., -2, -3, or even -99? Let’s check:</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.insert(-2, "Sam")
>>> lst
['Ann', 'Bob', 'Sam', 'Liz', 'Alice']</pre>
<p>… and …</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.insert(-3, "Bob")
>>> lst
['Ann', 'Bob', 'Bob', 'Sam', 'Liz', 'Alice']</pre>
<p>… and …</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.insert(-99, "Hans")
>>> lst
['Hans', 'Ann', 'Bob', 'Bob', 'Sam', 'Liz', 'Alice']</pre>
<p>So you can see that every integer index is allowed! If you overshoot (e.g. -99), it will simply insert at the beginning of the list.</p>
<h2>Python List insert() At Beginning</h2>
<p>The <code>insert()</code> method allows you to add an element at the beginning of a list. Simply use the index 0 in the call <code>lst.insert(0, element)</code> to add element to the beginning of the <code>lst</code>.</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 insert() At End</h2>
<p>Okay, you can insert an element at every position in the list—just use the first argument to define the insertion index. Consequently, you can “insert” an element at the end of a list by defining an index that’s greater or equal the size of the list. Remember, <code>insert(index, element)</code> inserts <code>element</code> <em>before </em>the element that’s currently at position <code>index</code>. So if you define an index that’s at least the size of the list, you’ll insert the element at the end of the list:</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, 4, 5, 6]
>>> lst.insert(6, 99)
>>> lst
[1, 2, 3, 4, 5, 6, 99]
>>> lst.insert(100000, 42)
>>> lst
[1, 2, 3, 4, 5, 6, 99, 42]</pre>
<p>No matter your concrete choice of the index argument, as long as it’s larger or equal the current size of the list, your element will be inserted at the end of the list.</p>
<p>However, this doesn’t make a lot of sense considering that you can use the <code>append(element)</code> method which adds an element at the end of the list—and is highly efficient (and readable). <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-append/" target="_blank">Read more about the <code>append()</code> method at my detailed blog article.</a></p>
<p>Here’s an example adding the same elements 99 and 42 to the end of the list:</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, 4, 5, 6]
>>> lst.append(99)
>>> lst.append(42)
>>> lst
[1, 2, 3, 4, 5, 6, 99, 42]</pre>
<p>In Python, there are usually a lot of ways to accomplish the same thing. Using the <code>append()</code> method to add an element to the end of the list is the better way!</p>
<h2>Python insert() into Sorted List</h2>
<p>How to insert an element into a sorted list (ascending order) and keep the list sorted? </p>
<p>The naive approach is to go over all elements, from first to last, as long as the element to be inserted is still smaller than the current element in the list. As soon as it’s larger, you go back one position and insert it there.</p>
<p>However, the computational complexity of the naive sorted insert algorithm is bad because you need up to n operations to insert an element into a list of n elements. </p>
<p>If you’re interested in the right way of doing it, you can use binary search and the <code>list.insert(i,x)</code> method to insert element <code>x</code> at position <code>i</code> in the list. Here’s the code for the binary search algorithm in Python:</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="">def binary_search(lst, value): lo, hi = 0, len(lst)-1 while lo &lt;= hi: mid = (lo + hi) // 2 if lst[mid] &lt; value: lo = mid + 1 elif value &lt; lst[mid]: hi = mid - 1 else: return mid return -1 l = [3, 6, 14, 16, 33, 55, 56, 89]
x = 56
print(binary_search(l,x))
# 6 (the index of the found element)</pre>
<p>Don’t worry if the code looks a bit complicated!</p>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/iterative-vs-recursive-binary-search-algorithms-in-python/" target="_blank">You can find a more detailed discussion of the binary search algorithm at my detailed tutorial on the Finxter blog.</a></p>
<h2>Python List insert() Multiple Elements</h2>
<p>How can you insert multiple elements into a list? Just call the <code>insert()</code> method multiple times—once for each element to be inserted! But be careful: you must reverse the order of the elements to be inserted first if you keep the insert position constant. Here’s what I mean:</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, 4]
>>> insert = [42, 99]
>>> insert.reverse()
>>> for el in insert: lst.insert(2, el) >>> lst
[1, 2, 42, 99, 3, 4]</pre>
<p>You want to insert elements 42 and 99 at position 2 of the list <code>lst</code>, in that order. If you’d just iterate over both elements, you’d first insert element 42 before index 2. Now, element 42 obtains the position 2 in the list. Next, you’d insert element 99 before position 2. Now, element 99 obtains position 2 in the list. So basically, you’ve reversed the original order of the elements to be inserted. Therefore, you have to call the <code>reverse()</code> method first before inserting the elements into the list.</p>
<p>There’s really no better alternative. Of course, you could use <a href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank" rel="noreferrer noopener">list concatenation</a> but that is not as efficient because you’d create a new list rather than modify an existing list:</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, 4]
>>> insert = [42, 99]
>>> lst = lst[:2] + insert + lst[2:]
>>> lst
[1, 2, 42, 99, 3, 4]</pre>
<p>This may be more readable but it’s not as efficient because list concatenation creates a new list each time it’s used. <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener">If you need to refresh your basic Python slicing skills (e.g. in the operation <code>lst[:2]</code>), check out this detailed blog tutorial.</a></p>
<h2>Python List insert() Complexity</h2>
<p><strong>Time Complexity: </strong>The <code>insert()</code> method has constant <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Time_complexity" target="_blank">time complexity</a> <em>O(1)</em> no matter the number of elements in the list. The reason is that <a rel="noreferrer noopener" href="https://docs.python.org/2/faq/design.html#how-are-lists-implemented" target="_blank">Python lists are implemented with variable-length array lists</a> so accessing a certain position is fast. Also inserting an element into the array list is fast because you only have to modify the pointers of the preceding and following elements in the list.</p>
<h2>Python List insert() vs append()</h2>
<p>The difference between the <code>append()</code> and the <code>insert()</code> method is the following:</p>
<ul>
<li>the <code>append(x)</code> method adds new element <code>x</code> to the end of the list, and</li>
<li>the <code>insert(i, x)</code> method adds new element <code>x</code> at position <code>i</code> in the list. It shifts all subsequent elements one position to the right.</li>
</ul>
<p>Here’s an example showing both <code>append()</code> and <code>insert()</code> methods in action:</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(99)
>>> l
[1, 2, 3, 99]
>>> l.insert(2, 42)
>>> l
[1, 2, 42, 3, 99]</pre>
<p>Both methods help you add new elements to the list. But you may ask:</p>
<p><strong>Which is faster, append() or insert()?</strong></p>
<p>All things being equal, the <code>append()</code> method is significantly faster than the <code>insert()</code> method. </p>
<p>Here’s a small script that shows that the <code>append()</code> method has a huge performance advantage over the <code>insert()</code> method when creating a list with 100,000 elements.</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 l1 = []
l2 = [] t1 = time.time() for i in range(100000): l1.append(i) t2 = time.time() for i in range(100000): l2.insert(0,i) t3 = time.time() print("append(): " + str(t2 - t1) + " seconds")
print("insert(): " + str(t3 - t2) + " seconds") # OUTPUT:
# append(): 0.015607357025146484 seconds
# insert(): 1.5420396327972412 seconds</pre>
<p>The experiments were performed on 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>
<h2>Alternatives: Python List append() vs extend()</h2>
<p>Instead of inserting an element, you can also add a single element to the end of the list using the <code>append()</code> method or even adding multiple elements to the end of the list using the <code>extend()</code> method. </p>
<p><strong>What’s the difference?</strong></p>
<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>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/append-1024x576.jpg" alt="" class="wp-image-6712" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/append-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/append-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/03/append-768x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<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, <code>extend()</code> and <code>append()</code>, 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—<code>append()</code> or <code>extend()</code>?</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 &amp; appends n elements''' lst = [] for i in range(n): lst.append(n) return lst def list_by_extend(n): '''Creates a list &amp; 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 insert() Returns None</h2>
<p>The return value of the <code>insert()</code> method is <code>None</code>. The return value of the <code>insert()</code> method is not a modified list with the added elements. Assuming this is a common source of mistakes.</p>
<p>Here’s such an error where the coder wrongly assumed this:</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].insert(1, 99)
>>> lst[0]
Traceback (most recent call last): File "&lt;pyshell#16>", line 1, in &lt;module> lst[0]
TypeError: 'NoneType' object is not subscriptable</pre>
<p> It doesn’t make sense to assign the result of the <code>insert()</code> method to another variable—because it’s always <code>None</code>. Instead, the <code>insert()</code> method changes a list object without creating (and returning) a new list.</p>
<p>Here’s the correct version of the same code:</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]
>>> lst.insert(1, 99)
>>> lst[1]
99</pre>
<p>Now, you change the list object itself by calling the <code>insert()</code> method on it. You through away the <code>None</code> return value because it’s not needed.</p>
<h2>Python List insert() Return New List</h2>
<p>If you use the <code>lst.insert(index, element)</code> operation, you add the <code>element</code> to the existing list <code>lst</code>. But what if you want to create a new list where all elements were added?</p>
<p>The answer is simply to use the <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">list concatenation</a> operation <code>lst[:index] + [element] + lst[index:]</code> which creates a new list each time it is used. The original list <code>lst</code> will not be affected by the list concatenation operation.</p>
<p>Here’s an example that shows that the <code>insert()</code> method only modifies an existing list:</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 = [1, 2, 3]
>>> lst_2 = lst_1.insert(1, 42)
>>> lst_1
[1, 42, 2, 3]
>>> lst_2
None</pre>
<p>And here’s the example that shows how to create a new list inserting element 42 at index 2:</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 = [1, 2, 3]
>>> lst_2 = lst_1[:1] + [42] + lst_1[1:]
>>> lst_1
[1, 2, 3]
>>> lst_2
[1, 42, 2, 3]</pre>
<p>By using the list concatenation operation, you can create a new list rather than inserting the element into an existing list.</p>
<h2>Python List insert() Thread Safe</h2>
<p>Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as <code>insert()</code>) are actually <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Thread_safety" target="_blank">thread safe</a>. </p>
<p>In other words: can you call the <code>insert()</code> operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)</p>
<p>The answer is yes (if you use the <a href="https://github.com/python/cpython" target="_blank" rel="noreferrer noopener">cPython </a>implementation). The reason is Python’s <a rel="noreferrer noopener" href="https://wiki.python.org/moin/GlobalInterpreterLock" target="_blank">global interpreter lock</a> that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation. </p>
<p>The only thing you need to know is that each basic operation in the cPython implementation is <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)" target="_blank">atomic</a>. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.</p>
<p><strong>All cPython operations are thread-safe. </strong>But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.</p>
<h2>Where to Go From Here?</h2>
<p>The <code>list.insert(index, element)</code> method inserts an <code>element</code> to the end of the <code>list</code> before the given <code>index</code> position.</p>
<p>You’ve learned the ins and outs of this important <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" target="_blank">Python list method</a>.</p>
<p>If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Python One-Liners</a> (Amazon Link). </p>
<p>In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!</p>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Get the book from Amazon!</a></p>
<p><strong>OFFICIAL BOOK DESCRIPTION:</strong> <em>Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.</em></p>
</div>


https://www.sickgaming.net/blog/2020/03/15/python-list-insert-method/