{"id":114072,"date":"2020-06-12T21:19:34","date_gmt":"2020-06-12T21:19:34","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9585"},"modified":"2020-06-12T21:19:34","modified_gmt":"2020-06-12T21:19:34","slug":"python-join-list-pairs","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/12\/python-join-list-pairs\/","title":{"rendered":"Python Join List Pairs"},"content":{"rendered":"<p class=\"has-background has-luminous-vivid-amber-background-color\"><strong>Given a list of strings. Join the first with the second string, the second with the third, and so on. The one-liner <code>[lst[i] + lst[i+1] for i in range(0, len(lst), 2)]<\/code> solves the problem by using the range function to iterate over every other index <code>i=0, 2, 4, 5, ...<\/code> to concatenate the <code>i<\/code>-th and the <code>i+1<\/code>-th elements in a list comprehension expression with <code>lst[i] + lst[i+1]<\/code>.<\/strong><\/p>\n<p>You may already know the normal <a href=\"https:\/\/blog.finxter.com\/python-join-list\/\" target=\"_blank\" rel=\"noreferrer noopener\">join function<\/a> in Python:<\/p>\n<h2>Intro: Python Join<\/h2>\n<p><strong>Problem<\/strong>: Given a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">list <\/a>of elements. How to join the elements by <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/concatenate-lists-in-python\/\" target=\"_blank\">concatenating<\/a> all elements in the list?<\/p>\n<p><strong>Example<\/strong>: You want to <a href=\"https:\/\/blog.finxter.com\/python-list-to-string\/\" target=\"_blank\" rel=\"noreferrer noopener\">convert list<\/a> <code>['learn ', 'python ', 'fast']<\/code> to the string <code>'learn python fast'<\/code>. <\/p>\n<p><strong>Quick Solution<\/strong>: to convert a list of strings to a string, do the following.<\/p>\n<ul>\n<li>Call the <code>''.join(list)<\/code> method on the empty string <code>''<\/code> that glues together all strings in the <code>list<\/code> and returns a new string. <\/li>\n<li>The string on which you call the join method is used as a delimiter between the list elements. <\/li>\n<li>If you don&#8217;t need a delimiter, just use the empty string <code>''<\/code>. <\/li>\n<\/ul>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the 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=\"\">lst = ['learn ', 'python ', 'fast']\nprint(''.join(lst))<\/pre>\n<p>The output 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=\"\">learn python fast<\/pre>\n<p>However, what if you want to do something different. Rather than joining all strings in the list to a single string, you want to join the strings in the list in pairs.<\/p>\n<h2>Problem: Python Join List Pairs<\/h2>\n<p><strong>Problem<\/strong>: Given a list of strings. Join the first with the second string, the second with the third, and so on. <\/p>\n<p><strong>Example<\/strong>: Let&#8217;s consider the following minimal example:<\/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=\"\">['x', 'y', 'v', 'w']<\/pre>\n<p>Is there any simple way to pair the first with the second and the third with the fourth string to obtain the following output?<\/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=\"\">['xy', 'vw']<\/pre>\n<p>Note that the length of the strings in the list is variable so the following would be a perfectly acceptable input:<\/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=\"\">['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff'] <\/pre>\n<p>You can play with all three methods before diving into each of them:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/1a68a6e75f\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: What&#8217;s the most Pythonic method?<\/em><\/p>\n<h2>Method 1: Zip() + List Comprehension<\/h2>\n<p>You can use the following smart one-liner solution<\/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=\"\">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']\nout = [x + y for x,y in zip(lst[::2], lst[1::2])]\nprint(out)\n# ['aaaab', 'ccdddd', 'eeefff']<\/pre>\n<p>The one-liner uses the following strategy:<\/p>\n<ul>\n<li>Obtain two slices <code>lst[::2]<\/code> and <code>lst[1::2]<\/code> of the original list over every other element starting from the first and the second elements, respectively. If you need to refresh your slicing skills, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" target=\"_blank\">check out my detailed blog article.<\/a><\/li>\n<li>Zip the two slices to a sequence of tuples using the <code>zip(...)<\/code> function. This aligns the first with the second elements from the original list, the third with the forth, and so on. To refresh your <code>zip()<\/code> skills, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" target=\"_blank\">check out my blog tutorial here.<\/a><\/li>\n<li>Use list comprehension to iterate over each pair of values <code>x,y<\/code> and concatenate them using list concatenation <code>x+y<\/code>. For a refresher on list comprehension, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">check out this free tutorial<\/a>&#8212;and for a refresher on list concatenation, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/concatenate-lists-in-python\/\" target=\"_blank\">check out this one<\/a>.<\/li>\n<\/ul>\n<h2>Method 2: Iterator + List Comprehension<\/h2>\n<p>You can also use an iterator to accomplish this:<\/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=\"\">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']\nit = iter(lst)\nout = [x + next(it, '') for x in it] print(out)\n# ['aaaab', 'ccdddd', 'eeefff']<\/pre>\n<p>Here&#8217;s the idea:<\/p>\n<ul>\n<li>Create an iterator object it using the built-in function <code>iter()<\/code>.<\/li>\n<li>Use list comprehension to go over each element in the iterator.<\/li>\n<li>Concatenate each element with the return value of calling the <code>next()<\/code> function on the iterator. This ensures that the iterator moves one position further iterating over the list. So, the next element <code>x<\/code> won&#8217;t be a duplicate.<\/li>\n<\/ul>\n<h2>Method 3: Use List Comprehension with Indexing<\/h2>\n<p>This method is the most straightforward one for Python beginners:<\/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=\"\">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']\nout = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]\nprint(out)\n# ['aaaab', 'ccdddd', 'eeefff']<\/pre>\n<p>The idea is simply to use the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-join-list-range-a-helpful-guide\/\" target=\"_blank\">range <\/a>function to iterate over every other index <code>i=0, 2, 4, 5, ...<\/code> to access the <code>i<\/code>-th and the <code>i+1<\/code>-th elements at the same time in the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">expression statement of list comprehension<\/a> (to <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-concatenation-add-vs-inplace-add-vs-extend\/\" target=\"_blank\">concatenate <\/a>those with <code>lst[i] + lst[i+1]<\/code>). <\/p>\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>Given a list of strings. Join the first with the second string, the second with the third, and so on. The one-liner [lst[i] + lst[i+1] for i in range(0, len(lst), 2)] solves the problem by using the range function to iterate over every other index i=0, 2, 4, 5, &#8230; to concatenate the i-th and [&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-114072","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\/114072","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=114072"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114072\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114072"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114072"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114072"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}