Sick Gaming
[Tut] Python Join List Range: A Helpful Guide - 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 Range: A Helpful Guide (/thread-95641.html)



[Tut] Python Join List Range: A Helpful Guide - xSicKxBot - 06-12-2020

Python Join List Range: A Helpful Guide

<div><p>If the search phrase<em> “Python Join List Range”</em> brought you here, you’re having most likely one of the following problems:</p>
<ol>
<li>You don’t know how to <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenate </a>two <code>range()</code> iterables, or</li>
<li>You want to use <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-join-list/" target="_blank">.join()</a></code> to create a string from a <code>range()</code> iterable—but it doesn’t work.</li>
</ol>
<p>In any case, by reading this article, I hope that you’ll not only answer your question, you’re also become a slightly better (Python) coder by understanding important nuances in the<a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener"> Python programming language</a>.</p>
<p>But let’s first play with some code and get an overview of the two solutions, shall we?</p>
<p> <iframe src="https://trinket.io/embed/python/e36ce7dbd8" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Can you accomplish both objectives in a single line of Python code?</em></p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/graphic-1024x576.jpg" alt="Python Join List Range" class="wp-image-9484" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/graphic-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/graphic-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/graphic-768x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<h2>Concatenate Two range() Iterables</h2>
<p><strong>Problem</strong>: How to create a new list by concatenating two <code>range()</code> iterables?</p>
<p><strong>Example</strong>: You want to concatenate the following two <code>range()</code> iterables</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="">range(1,5) + range(5,10)</pre>
<p>Your expected result is:</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="">[1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<p><strong>Developing the Solution</strong>: The result of the <code>range(start, stop, step)</code> function is an iterable “range” object:</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="">>>> range(10)
range(0, 10)
>>> type(range(10))
&lt;class 'range'></pre>
<p>Unfortunately, you cannot simply concatenate two range objects because this would cause a <code>TypeError</code>—the + operator is not defined on two range objects:</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="">>>> range(1, 5) + range(5, 10)
Traceback (most recent call last): File "&lt;pyshell#2>", line 1, in &lt;module> range(1, 5) + range(5, 10)
TypeError: unsupported operand type(s) for +: 'range' and 'range'</pre>
<p>Thus, the easiest way to concatenate two range objects is to do the following.</p>
<ul>
<li>Convert both range objects to lists using the <code>list(range(...))</code> function calls.</li>
<li>Use the <a href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/" target="_blank" rel="noreferrer noopener">list concatenation</a> operator <code>+</code> on the resulting objects.</li>
</ul>
<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 = list(range(1, 5)) + list(range(5, 10))
print(l)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<p>There are other ways to <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenate lists</a>—and a more efficient one is to use the <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/itertools.html#itertools.chain" target="_blank">itertools.chain()</a></code> function.</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="">from itertools import chain
l = chain(range(1, 5), range(5, 10))
print(list(l))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<p>This has the advantage that you work purely on iterables rather than <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>. There’s no need to waste computational cycles to create a list object if you need it only to <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/" target="_blank">concatenate </a>it to another list object. By avoiding the superfluous list creation, you win in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-cprofile-a-helpful-guide-with-prime-example/" target="_blank">performance </a>(at the costs of adding another <a rel="noreferrer noopener" href="https://blog.finxter.com/the-complete-python-library-guide/" target="_blank">library </a>to your code). </p>
<p>You can see how the first version creates multiple list objects in memory in the interactive memory visualizer:</p>
<p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=l1%20%3D%20list%28range%281,%205%29%29%20%0Al2%20%3D%20list%28range%285,%2010%29%29%0Al%20%3D%20l1%20%2B%20l2%0Aprint%28l%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=3&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<p><em><strong>Exercise</strong>: How many list objects are there in memory after the code terminates?</em></p>
<h2>Use .join() to Create a String From a range() Iterable</h2>
<p><strong>Problem</strong>: Given a range object—which is an iterable of integers—how to join all integers into a new string variable?</p>
<p><strong>Example</strong>: You have the following range object:</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="">range(10)</pre>
<p>You want the following string:</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="">'0123456789'</pre>
<p><strong>Solution</strong>: To convert a range object to a string, use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-join-list/" target="_blank"><code>string.join()</code></a> method and pass the <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">generator expression</a> <code>str(x) for x in range(...)</code> to convert each integer to a string value first. This is necessary as the join function expects an iterable of strings and not integers. If you miss this second step, Python will throw a <code>TypeError</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="">print(''.join(range(10))) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in &lt;module> print(''.join(range(10)))
TypeError: sequence item 0: expected str instance, int found '''</pre>
<p>So, the correct way is to convert each element to a string using the <a href="https://blog.finxter.com/how-to-use-generator-expressions-in-python-dictionaries/" target="_blank" rel="noreferrer noopener">generator expression</a> <code>str(x) for x in range(...)</code> inside the <code>join(...)</code> argument list. Here’s the correct code that joins together all integers in a range object in the most Pyhtonic way:</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="">print(''.join(str(x) for x in range(10))) '0123456789'</pre>
<p>You can use different <a href="https://blog.finxter.com/convert-list-of-tuples-to-string/" target="_blank" rel="noreferrer noopener">delimiter </a>strings if you need to:</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="">print('-'.join(str(x) for x in range(10))) '0-1-2-3-4-5-6-7-8-9'</pre>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">Python Lists [Ultimate Guide]</a></li>
<li><a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">Python Join [Ultimate Guide]</a></li>
<li><a href="https://blog.finxter.com/which-is-faster-list-comprehension-or-map-function-in-python/" target="_blank" rel="noreferrer noopener">Python Generator Expressions and List Comprehension</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/10/python-join-list-range-a-helpful-guide/