{"id":112952,"date":"2020-05-15T11:44:43","date_gmt":"2020-05-15T11:44:43","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=8564"},"modified":"2020-05-15T11:44:43","modified_gmt":"2020-05-15T11:44:43","slug":"how-to-add-an-element-to-a-python-list-at-an-index","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/05\/15\/how-to-add-an-element-to-a-python-list-at-an-index\/","title":{"rendered":"How to Add an Element to a Python List at an Index?"},"content":{"rendered":"<p><strong>To add an element to a given Python list, you can use either of the three following methods:<\/strong><\/p>\n<ol>\n<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>\n<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>\n<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>\n<\/ol>\n<p>In the following, you&#8217;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 &#8220;Run&#8221; to see the output):<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/37221a165c\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<h2>Method 1: insert(index, element)<\/h2>\n<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>\n<p>Here&#8217;s an example with comments:<\/p>\n<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\nlst = [2, 4, 6, 8] # Insert string at index 2\nlst.insert(2, 'Alice') # Print modified list object\nprint(lst)\n# [2, 4, 'Alice', 6, 8]<\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Properties of <code>insert()<\/code><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Operates on existing list object<\/td>\n<\/tr>\n<tr>\n<td>Simple<\/td>\n<\/tr>\n<tr>\n<td>Fast<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Check out the objects in memory while executing this code snippet (in comparison to the other methods discussed in this article):<\/p>\n<p> <iframe loading=\"lazy\" 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&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=0&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<p>Click &#8220;Next&#8221; to move on in the code and observe the memory objects creation.<\/p>\n<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>\n<h2>Method 2: Slice Assignment<\/h2>\n<p>Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. <\/p>\n<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>\n<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>\n<p>Here&#8217;s another example that shows you how to insert the string <code>'Alice'<\/code> into a list with four integers.<\/p>\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/05\/sliceAssignment-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/sliceAssignment-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p>Let&#8217;s have a look at the code:<\/p>\n<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\nlst = [2, 4, 6, 8] # Insert string at index 2\nlst[2:2] = ['Alice'] # Print modified list object\nprint(lst)\n# [2, 4, 'Alice', 6, 8]<\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Properties of Slice Assignment<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Operates on existing list object<\/td>\n<\/tr>\n<tr>\n<td>Slightly more complex<\/td>\n<\/tr>\n<tr>\n<td>Fast<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p><strong>Related article<\/strong>: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-slice-assignment\/\" target=\"_blank\">Python Slice Assignment<\/a><\/p>\n<h2>Method 3: List Concatenation<\/h2>\n<p>If you use the <code>+<\/code> operator on two integers, you\u2019ll get the sum of those integers. But if you use the <code>+<\/code> operator on two lists, you\u2019ll get a new list that is the concatenation of those lists.<\/p>\n<p>Here&#8217;s the same example, you&#8217;ve already seen in the previous sections:<\/p>\n<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\nlst = [2, 4, 6, 8] # Insert string at index 2\nlst = lst[:2] + ['Alice'] + lst[2:] # Print modified list object\nprint(lst)\n# [2, 4, 'Alice', 6, 8]<\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Properties of List Concatenation<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Creates a new list object<\/td>\n<\/tr>\n<tr>\n<td>Slightly more complex<\/td>\n<\/tr>\n<tr>\n<td>Slower<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>To add an element to a given Python list, you can use either of the three following methods: Use the list insert method list.insert(index, element). Use slice assignment lst[index:index] = [element] to overwrite the empty slice with a list of one element. Use list concatenation with slicing lst[:2] + [&#8216;Alice&#8217;] + lst[2:] to create a [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-112952","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112952","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=112952"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112952\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=112952"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=112952"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=112952"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}