Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] The Most Pythonic Way to Join a List in Reverse Order

#1
The Most Pythonic Way to Join a List in Reverse Order

<div><p class="has-background has-luminous-vivid-amber-background-color"><strong>The most efficient method to join a list of Python strings in reverse order is to use the Python code <code>''.join(l[::-1])</code>. First, reverse the list <code>l</code> using slicing with a negative step size <code>l[::-1]</code>. Second, glue together the strings in the list using the <code>join(...)</code> method on the empty string <code>''</code>.</strong></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="The Most Pythonic Way to Join a List in Reverse Order" width="1400" height="788" src="https://www.youtube.com/embed/brhppRcRpis?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: Given a list of strings. How to join the strings in reverse order?</p>
<p><strong>Example</strong>: You want to join 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="">l = ['n', 'o', 'h', 't', 'y', 'p']</pre>
<p>to obtain the joined string in reverse order</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="">python</pre>
<p>Let’s get a short overview on how to accomplish this.</p>
<p><strong>Solution Overview</strong>: You can try the three methods in our interactive Python shell.</p>
<p> <iframe src="https://trinket.io/embed/python/8a6ba00cf3" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p>Next, we’ll dive into each method separately.</p>
<h2>Method 1: Join + Slicing</h2>
<p>The first and most Pythonic method to reverse and join a list of strings is to use slicing with a <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-negative-indexing/" target="_blank">negative step size</a>. </p>
<p>You can slice any list in Python using the notation <code>list[start:stop:step]</code> to create a sublist starting with index <code>start</code>, ending right before index <code>stop</code>, and using the given <code>step</code> size—which can also be negative to slice from right to left. If you need a refresher on slicing, check out our <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">detailed Finxter blog tutorial</a> or our focused book <a rel="noreferrer noopener" href="https://blog.finxter.com/coffee-break-python/" target="_blank">“Coffee Break Python Slicing”</a>.</p>
<p>Here’s the first method to reverse a list of strings and join the elements together:</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 = ['n', 'o', 'h', 't', 'y', 'p'] # Method 1
print(''.join(l[::-1]))
# python</pre>
<p>The <code>string.join(iterable)</code> method joins the string elements in the <code>iterable</code> to a new string by using the <code>string</code> on which it is called as a delimiter. </p>
<p>You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code><code>string.join(iterable)</code></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>The elements to be concatenated.</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-join-list/" target="_blank">Python Join List [Ultimate Guide]</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Python Slicing [Ultimate Guide]</a></li>
<li><a href="https://blog.finxter.com/python-list-reverse/" target="_blank" rel="noreferrer noopener">How to Reverse a Python List</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">The Ultimate Guide to Python Lists</a></li>
</ul>
<h2>Method 2: Join + reversed()</h2>
<p>The second method is also quite Pythonic: using the <code>reversed()</code> built-in function rather than slicing with a negative step size. I’d say that beginners generally prefer this method because it’s more readable to them—while expert coders prefer slicing because it’s more concise and slightly more efficient.</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 = ['n', 'o', 'h', 't', 'y', 'p']
print(''.join(reversed(l)))
# python</pre>
<p>The join method glues together all strings in the list—in <em>reversed</em> order!</p>
<h2>Method 3: Simple Loop</h2>
<p>The third method is the least Pythonic one: using a <a href="https://blog.finxter.com/python-loops/">loop </a>where it’s not really needed. Anyways, especially coders coming from other <a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" target="_blank" rel="noreferrer noopener">programming languages</a> like Java or C++ will often use this approach.</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 = ['n', 'o', 'h', 't', 'y', 'p'] s = ''
for x in reversed(l): s += x
print(s)
# python
</pre>
<p>However, there are several disadvantages. Can you see them?</p>
<ul>
<li>The code is less concise.</li>
<li>The code is less efficient because of the repeated string concatenation. Each loop execution causes the creation of a new string, which is highly inefficient.</li>
<li>The code requires the definition of two new variables <code>x</code> and <code>s</code> and introduces a higher level of <a rel="noreferrer noopener" href="https://blog.finxter.com/complexity-of-python-operations/" target="_blank">complexity</a>.</li>
</ul>
<p>You can see this in our interactive memory visualizer:</p>
<p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=l%20%3D%20%5B'n',%20'o',%20'h',%20't',%20'y',%20'p'%5D%0As%20%3D%20''%0Afor%20x%20in%20reversed%28l%29%3A%0A%20%20%20%20s%20%2B%3D%20x%0Aprint%28s%29%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><em><strong>Exercise</strong>: click “Next” to see the memory objects used in this code snippet!</em></p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-profilers-how-to-speed-up-your-python-app/" target="_blank">Performance Tuning in Python</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/" target="_blank">List Concatenation</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-built-in-string-functions-simply-explained/" target="_blank">Python Built-in String Functions</a></li>
</ul>
<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/...rse-order/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016