Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Add an Element to a Python List at an Index?

#1
How to Add an Element to a Python List at an Index?

<div><p><strong>To add an element to a given Python list, you can use either of the three following methods:</strong></p>
<ol>
<li><strong>Use the <a href="https://blog.finxter.com/python-list-insert-method/" target="_blank" rel="noreferrer noopener">list insert</a> method <code>list.insert(index, element)</code>.</strong></li>
<li><strong>Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-slice-assignment/" target="_blank">slice assignment</a> <code>lst[index:index] = [element]</code> to overwrite the empty slice with a list of one element.</strong></li>
<li><strong>Use <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">list concatenation</a> with slicing <code>lst[:2] + ['Alice'] + lst[2:]</code> to create a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list </a>object.</strong></li>
</ol>
<p>In the following, you’ll learn about all three methods in greater detail. But before that, feel free to test those yourself in our interactive Python shell (just click “Run” to see the output):</p>
<p> <iframe src="https://trinket.io/embed/python/37221a165c" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<h2>Method 1: insert(index, element)</h2>
<p>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.</p>
<p>Here’s an example with comments:</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=""># Create the list
lst = [2, 4, 6, 8] # Insert string at index 2
lst.insert(2, 'Alice') # Print modified list object
print(lst)
# [2, 4, 'Alice', 6, 8]</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Properties of <code>insert()</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>Operates on existing list object</td>
</tr>
<tr>
<td>Simple</td>
</tr>
<tr>
<td>Fast</td>
</tr>
</tbody>
</table>
</figure>
<p>Check out the objects in memory while executing this code snippet (in comparison to the other methods discussed in this article):</p>
<p> <iframe width="800" height="700" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=%0A%23%20METHOD%201%3A%20list.insert%28index,%20element%29%0Alst%20%3D%20%5B2,%204,%206,%208%5D%0Alst.insert%282,%20'Alice'%29%0Aprint%28lst%29%0A%23%20%5B2,%204,%20'Alice',%206,%208%5D%0A%0A%0A%0A%23%20METHOD%202%3A%20slice%20assignment%0Alst%20%3D%20%5B2,%204,%206,%208%5D%0Alst%5B2%3A2%5D%20%3D%20%5B'Alice'%5D%0Aprint%28lst%29%0A%23%20%5B2,%204,%20'Alice',%206,%208%5D%0A%0A%0A%0A%23%20METHOD%203%3A%20list%20concatenation%0Alst%20%3D%20%5B2,%204,%206,%208%5D%0Alst%20%3D%20lst%5B%3A2%5D%20%2B%20%5B'Alice'%5D%20%2B%20lst%5B2%3A%5D%0Aprint%28lst%29%0A%23%20%5B2,%204,%20'Alice',%206,%208%5D%0A&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<p>Click “Next” to move on in the code and observe the memory objects creation.</p>
<p><strong>Related article</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-insert-method/" target="_blank">Python List insert() Method</a></p>
<h2>Method 2: Slice Assignment</h2>
<p>Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. </p>
<p>Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation. </p>
<p>For example, the slice assignment <code>list[2:4] = [42, 42]</code> replaces the list elements with index <code>2</code> and <code>3</code> with the value <code>42</code>.</p>
<p>Here’s another example that shows you how to insert the string <code>'Alice'</code> into a list with four integers.</p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/sliceAssignment-1024x576.jpg" alt="" class="wp-image-8572" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/sliceAssignment-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p>Let’s have a look at the 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=""># Create the list
lst = [2, 4, 6, 8] # Insert string at index 2
lst[2:2] = ['Alice'] # Print modified list object
print(lst)
# [2, 4, 'Alice', 6, 8]</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Properties of Slice Assignment</th>
</tr>
</thead>
<tbody>
<tr>
<td>Operates on existing list object</td>
</tr>
<tr>
<td>Slightly more complex</td>
</tr>
<tr>
<td>Fast</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Related article</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-slice-assignment/" target="_blank">Python Slice Assignment</a></p>
<h2>Method 3: List Concatenation</h2>
<p>If you use the <code>+</code> operator on two integers, you’ll get the sum of those integers. But if you use the <code>+</code> operator on two lists, you’ll get a new list that is the concatenation of those lists.</p>
<p>Here’s the same example, you’ve already seen in the previous sections:</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=""># Create the list
lst = [2, 4, 6, 8] # Insert string at index 2
lst = lst[:2] + ['Alice'] + lst[2:] # Print modified list object
print(lst)
# [2, 4, 'Alice', 6, 8]</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Properties of List Concatenation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Creates a new list object</td>
</tr>
<tr>
<td>Slightly more complex</td>
</tr>
<tr>
<td>Slower</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Related article</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">How to Concatenate Lists in Python? [Interactive Guide]</a></p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/05/...-an-index/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016