Sick Gaming
[Tut] Python Join List Slice - 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 Join List Slice (/thread-95675.html)



[Tut] Python Join List Slice - xSicKxBot - 06-14-2020

Python Join List Slice

<div><p class="has-background has-luminous-vivid-amber-background-color"><strong>To join and replace all strings in a list <strong><code><strong><strong><code>lst</code></strong></strong></code></strong> between start index 1 and end index 5, use the one-liner <code>lst[1:5] = [''.join(lst[1:5])]</code>. This solution is based on slice assignment that selects the slice you want to replace on the left and the values to replace it on the right side of the assignment.</strong></p>
<p><strong>Problem</strong>: Given a list of strings. How to join all strings in a given list slice and replace the slice with the joined string?</p>
<p><strong>Example</strong>:You start with the following 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 = ['i', 'l', 'o', 'v', 'e', 'u']</pre>
<p>You want to join the slice <code>['l', 'o', 'v', 'e']</code> with start index 1 and end index 4 (included) and replace it in the list to obtain the result:</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=""># Output: ['i', 'love', 'u']</pre>
<p>You can get a quick overview of all three methods in the following interactive Python shell. If you’re short on time—method 1 using slice assignment is the most Pythonic solution!</p>
<p> <iframe src="https://trinket.io/embed/python/a7c4fa6ef4" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Modify the code so that only elements with start index 2 and end index 4 (included) are replaced by the joined string!</em></p>
<h2>Method 1: Slice Assignment</h2>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/python-slice-assignment/" target="_blank">Slice assignment</a> is a little-used, beautiful Python feature to replace a slice with another sequence. Select the slice you want to <a href="https://blog.finxter.com/python-string-replace/" target="_blank" rel="noreferrer noopener">replace </a>on the left and the values to replace it on the right side of the equation.</p>
<p>Here’s how you can join and replace all strings in a list slice (between indices 1 and 5) in a <a rel="noreferrer noopener" href="https://blog.finxter.com/10-python-one-liners/" target="_blank">single line</a> of Python 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 1: Slice Assignments
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst[1:5] = [''.join(lst[1:5])]
print(lst)
# ['i', 'love', 'u']</pre>
<p>The one-liner <code>lst[1:5] = [''.join(lst[1:5])]</code> performs the following steps:</p>
<ul>
<li>Select the slice to be replaced on the left-hand side of the equation with <code>lst[1:5]</code>. <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener">Read more about slicing on my Finxter blog tutorial.</a></li>
<li>Create a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list </a>that replaces this slice on the right-hand side of the equation with <code>[...]</code>. </li>
<li>Select the slice of string elements to be <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">joined </a>together (<code>'l', 'o', 'v', 'e'</code>) with <code>lst[1:5]</code>. </li>
<li>Pass this slice into the join function to create a new string with all four characters <code>'love'</code>. </li>
<li>This string replaces all four selected positions in the original list. </li>
</ul>
<p>If you love the power of Python one-liners, check out my new book with the same name <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">“Python One-Liners”</a> on Amazon (published in 2020 with San Francisco’s high-quality NoStarch publishing house). </p>
<h2>Method 2: List Concatenation + Slicing + Join</h2>
<p>A simpler but quite readable method is to use simple list concatenation. Read more on my Finxter blog tutorial to <a href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank" rel="noreferrer noopener">master all different ways to concatenate lists in Python.</a></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 2: List Concatenation + Join
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst = lst[:1] + [''.join(lst[1:5])] + lst[5:]
print(lst)
# ['i', 'love', 'u']</pre>
<p>This approach uses three slicing calls to select (or create) three lists. Then, it glues them together using the <code>+</code> operator. This approach has the slight disadvantage that a new list is created in memory (rather than working on the old list). Thus, it’s slightly less memory-friendly as the first method.</p>
<h2>Method 3: Naive</h2>
<p>This method is what a <a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" target="_blank" rel="noreferrer noopener">non-Python</a> coder (maybe coming from Java or C++) would use. It’s NOT the recommended way though.</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 3: Naive
lst = ['i', 'l', 'o', 'v', 'e', 'u']
new = ''
for i in range(1,5): new += lst[i]
lst = lst[:1] + [new] + lst[5:]
print(lst)
# ['i', 'love', 'u']</pre>
<p>Instead of selecting the slice of strings to be joined using <a href="https://blog.finxter.com/free-book-coffee-break-python-slicing/" target="_blank" rel="noreferrer noopener">slicing</a>, the coder creates a string variable <code>new</code> and adds one character at-a-time. This is very inefficient as many different strings are created—each time one adds one more character to the string.</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/06/13/python-join-list-slice/