{"id":113992,"date":"2020-06-10T07:41:10","date_gmt":"2020-06-10T07:41:10","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9464"},"modified":"2020-06-10T07:41:10","modified_gmt":"2020-06-10T07:41:10","slug":"python-join-list-range-a-helpful-guide","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/10\/python-join-list-range-a-helpful-guide\/","title":{"rendered":"Python Join List Range: A Helpful Guide"},"content":{"rendered":"<p>If the search phrase<em> &#8220;Python Join List Range&#8221;<\/em> brought you here, you&#8217;re having most likely one of the following problems:<\/p>\n<ol>\n<li>You don&#8217;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>\n<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&#8212;but it doesn&#8217;t work.<\/li>\n<\/ol>\n<p>In any case, by reading this article, I hope that you&#8217;ll not only answer your question, you&#8217;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>\n<p>But let&#8217;s first play with some code and get an overview of the two solutions, shall we?<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/e36ce7dbd8\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Can you accomplish both objectives in a single line of Python code?<\/em><\/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\/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=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<h2>Concatenate Two range() Iterables<\/h2>\n<p><strong>Problem<\/strong>: How to create a new list by concatenating two <code>range()<\/code> iterables?<\/p>\n<p><strong>Example<\/strong>: You want to concatenate the following two <code>range()<\/code> iterables<\/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=\"\">range(1,5) + range(5,10)<\/pre>\n<p>Your expected result is:<\/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=\"\">[1, 2, 3, 4, 5, 6, 7, 8, 9]<\/pre>\n<p><strong>Developing the Solution<\/strong>: The result of the <code>range(start, stop, step)<\/code> function is an iterable &#8220;range&#8221; object:<\/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=\"\">>>> range(10)\nrange(0, 10)\n>>> type(range(10))\n&lt;class 'range'><\/pre>\n<p>Unfortunately, you cannot simply concatenate two range objects because this would cause a <code>TypeError<\/code>&#8212;the + operator is not defined on two range objects:<\/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=\"\">>>> range(1, 5) + range(5, 10)\nTraceback (most recent call last): File \"&lt;pyshell#2>\", line 1, in &lt;module> range(1, 5) + range(5, 10)\nTypeError: unsupported operand type(s) for +: 'range' and 'range'<\/pre>\n<p>Thus, the easiest way to concatenate two range objects is to do the following.<\/p>\n<ul>\n<li>Convert both range objects to lists using the <code>list(range(...))<\/code> function calls.<\/li>\n<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>\n<\/ul>\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=\"\">l = list(range(1, 5)) + list(range(5, 10))\nprint(l)\n# [1, 2, 3, 4, 5, 6, 7, 8, 9]<\/pre>\n<p>There are other ways to <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/concatenate-lists-in-python\/\" target=\"_blank\">concatenate lists<\/a>&#8212;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>\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=\"\">from itertools import chain\nl = chain(range(1, 5), range(5, 10))\nprint(list(l))\n# [1, 2, 3, 4, 5, 6, 7, 8, 9]<\/pre>\n<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&#8217;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>\n<p>You can see how the first version creates multiple list objects in memory in the interactive memory visualizer:<\/p>\n<p> <iframe loading=\"lazy\" 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&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=3&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: How many list objects are there in memory after the code terminates?<\/em><\/p>\n<h2>Use .join() to Create a String From a range() Iterable<\/h2>\n<p><strong>Problem<\/strong>: Given a range object&#8212;which is an iterable of integers&#8212;how to join all integers into a new string variable?<\/p>\n<p><strong>Example<\/strong>: You have the following range object:<\/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=\"\">range(10)<\/pre>\n<p>You want the following string:<\/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=\"\">'0123456789'<\/pre>\n<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>\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=\"\">print(''.join(range(10))) '''\nTraceback (most recent call last): File \"C:\\Users\\xcent\\Desktop\\code.py\", line 2, in &lt;module> print(''.join(range(10)))\nTypeError: sequence item 0: expected str instance, int found '''<\/pre>\n<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&#8217;s the correct code that joins together all integers in a range object in the most Pyhtonic way:<\/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=\"\">print(''.join(str(x) for x in range(10))) '0123456789'<\/pre>\n<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>\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=\"\">print('-'.join(str(x) for x in range(10))) '0-1-2-3-4-5-6-7-8-9'<\/pre>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/python-join-list\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Lists [Ultimate Guide]<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-join-list\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Join [Ultimate Guide]<\/a><\/li>\n<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>\n<\/ul>\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>If the search phrase &#8220;Python Join List Range&#8221; brought you here, you&#8217;re having most likely one of the following problems: You don&#8217;t know how to concatenate two range() iterables, or You want to use .join() to create a string from a range() iterable&#8212;but it doesn&#8217;t work. In any case, by reading this article, I hope [&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-113992","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\/113992","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=113992"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/113992\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=113992"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=113992"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=113992"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}