Create an account


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

#1
How to Add Elements to a List in Python?

<div><p>In Python, there are always multiple ways to accomplish the same thing—but with subtle differences in the side effects. A great coder will always choose the most effective way for the problem at hand.</p>
<p>This tutorial shows you six different ways to add elements to a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list </a>in Python. In a nutshell, the different ways to add one or more elements to a list are:</p>
<ol>
<li><strong><a href="https://blog.finxter.com/python-list-append/" target="_blank" rel="noreferrer noopener">append()</a></strong>: add a single element to an existing list. </li>
<li><strong><a href="https://blog.finxter.com/python-list-extend/">extend()</a></strong>: add multiple elements to an existing list. </li>
<li><strong><a href="https://blog.finxter.com/python-list-insert-method/">insert()</a></strong>: add an element at an arbitrary position in an existing list. </li>
<li><strong><a href="https://blog.finxter.com/python-slice-assignment/">Slice assignment</a>:</strong> replace a slice of an existing list. </li>
<li><strong><a href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/">List concatenation with +</a>:</strong> add one or more elements to a new list. </li>
<li><strong><a href="https://blog.finxter.com/what-is-asterisk-in-python/">Asterisk operator *</a>: </strong>unpack multiple iterables into a new list.</li>
</ol>
<p><strong>Try It Yourself</strong>: Before we dive into each of those methods, let’s try them yourself in our interactive Python shell!</p>
<p> <iframe src="https://trinket.io/embed/python/034f6bf94e" width="100%" height="700" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Use each method to add yet another integer element <code>42</code> to each list. Which method is the best one to add multiple elements?</em></p>
<p>Next, you’ll learn about each method in a video tutorial and short example code snippet. I’ve written in-depth articles for each method so feel free to follow the references given in each method.</p>
<h2>Method 1: append()</h2>
<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() Method" width="1400" height="788" src="https://www.youtube.com/embed/0fteTqtUUik?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<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>. You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.append(element)</code></p>
<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>
<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=""># Method 1: append()
friends = ['Alice', 'Bob', 'Ann']
friends.append('Liz') print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz']</pre>
<p><strong>Read More</strong>: <a href="https://blog.finxter.com/python-list-append/" target="_blank" rel="noreferrer noopener">Python List append() Method</a></p>
<h2>Method 2: extend()</h2>
<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 extend() Method [No-BS]" width="1400" height="788" src="https://www.youtube.com/embed/o-zrozPt_CY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>The <code>list.extend(iter)</code> method adds all elements in the argument iterable <code>iter</code> to an existing <code>list</code>. You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.extend(iterable)</code></p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>iterable</code></td>
<td>All the elements of the <a href="https://docs.python.org/3/glossary.html" target="_blank" rel="noreferrer noopener">iterable </a>will be added to the end of the list—in the order of their occurrence.</td>
</tr>
</tbody>
</table>
</figure>
<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=""># Method 2: extend()
friends = ['Alice', 'Bob', 'Ann']
friends.extend(['Liz', 'Carl']) print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz', 'Carl']</pre>
<p><strong>Read More</strong>: <a href="https://blog.finxter.com/python-list-extend/" target="_blank" rel="noreferrer noopener">Python List extend() Method</a></p>
<h2>Method 3: insert()</h2>
<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 insert() Method" width="1400" height="788" src="https://www.youtube.com/embed/gqwqqwRinNE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<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. You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.insert(index, element)</code></p>
<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>
<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=""># Method 3: insert()
friends = ['Alice', 'Bob', 'Ann']
friends.insert(3, 'Liz') print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz']</pre>
<p><strong>Read More</strong>: <a href="https://blog.finxter.com/python-list-insert-method/" target="_blank" rel="noreferrer noopener">Python List insert() Method</a></p>
<h2>Method 4: Slice Assignment</h2>
<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 One-Liners - Trick 6 - Slice Assignment to Clean Corrupted Browser Data" width="1400" height="788" src="https://www.youtube.com/embed/6LU_Aiq3lT4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation. 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>
<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=""># Method 4: slice assignment
friends = ['Alice', 'Bob', 'Ann']
friends[3:3] = ['Liz'] print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz']</pre>
<p><strong>Read More</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-append/" target="_blank">Python Slice Assignment</a></p>
<h2>Method 5: List Concatenation with +</h2>
<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="How to Concatenate Lists in Python? [Interactive Guide]" width="1400" height="788" src="https://www.youtube.com/embed/9rrqInUeG8U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<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>
<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=""># Method 5: list concatenation
friends = ['Alice', 'Bob', 'Ann']
friends = friends + ['Liz'] print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz']</pre>
<p><strong>Read More</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-append/" target="_blank">Python List Concatenation</a></p>
<h2>Method 6: List Concatenation with Unpacking *</h2>
<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="Asterisk operator" width="1400" height="788" src="https://www.youtube.com/embed/-nLkYmIevwY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>There are many applications of the asterisk operator. But one nice trick is to use it as an unpacking operator that “unpacks” the contents of a container data structure such as a list or a dictionary into another one.</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=""># Method 6: unpacking
friends = ['Alice', 'Bob', 'Ann']
friends = [*friends, 'Liz'] print(friends)
# ['Alice', 'Bob', 'Ann', 'Liz']</pre>
<p>A great advantage is that you can quickly unpack all elements of two or more list into a new list. </p>
<p><strong>Read More</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">Python Unpacking with Asterisk</a></p>
<h2>Python List Methods Cheat Sheet</h2>
<p>Here’s your free<a href="https://blog.finxter.com/python-list-methods/" target="_blank" rel="noreferrer noopener"> </a>PDF <a href="https://blog.finxter.com/python-list-methods-cheat-sheet-instant-pdf-download/" target="_blank" rel="noreferrer noopener">cheat sheet showing you all Python list methods</a> on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.pdf" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.jpg" alt="" class="wp-image-7544" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.jpg 670w, https://blog.finxter.com/wp-content/uplo...31x300.jpg 231w" sizes="(max-width: 670px) 100vw, 670px" /></a></figure>
</div>
<div class="wp-block-buttons aligncenter">
<div class="wp-block-button"><a class="wp-block-button__link has-background has-vivid-cyan-blue-background-color" href="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.pdf" style="border-radius:9px" target="_blank" rel="noreferrer noopener">Instant PDF Download [100% FREE]</a></div>
</div>
<h2>Discussion</h2>
<p>Let’s summarize the strengths and weaknesses of the different methods:</p>
<ol>
<li>Use the <code>append()</code> method to <strong>add a single element </strong>to an existing list without creating a new list.</li>
<li>Use the <code>extend()</code> method to <strong>add multiple elements</strong> to an existing list without creating a new list.</li>
<li>Use the <code>insert()</code> method to <strong>add an element at an arbitrary position</strong> in the list—without creating a new list.</li>
<li>Use slice assignment to <strong>replace a slice </strong>of an existing list—without creating a new list.</li>
<li>Use list concatenation with <code>+</code> to add <strong>one or more elements</strong> to a list—if you want to <strong>create a new list</strong>.</li>
<li>Use the asterisk operator <code>*</code> to unpack <strong>multiple iterables</strong> into a new list—if you want to <strong>create a new list</strong>.</li>
</ol>
<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/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016