{"id":114399,"date":"2020-06-20T15:11:07","date_gmt":"2020-06-20T15:11:07","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9927"},"modified":"2020-06-20T15:11:07","modified_gmt":"2020-06-20T15:11:07","slug":"the-most-pythonic-way-to-convert-a-list-to-a-string","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/20\/the-most-pythonic-way-to-convert-a-list-to-a-string\/","title":{"rendered":"The Most Pythonic Way to Convert a List to a String"},"content":{"rendered":"<p class=\"has-black-color has-luminous-vivid-amber-background-color has-text-color has-background\"><strong>To convert a list <code>lst<\/code> of strings to a string, use the <code>''.join(lst)<\/code> method with an empty separator string between the elements. If you have a list of objects, first convert each element to a string and join the result with the generator expression <code>''.join(str(x) for x in lst)<\/code>. <\/strong><\/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\/list2string-1024x576.jpg\" alt=\"\" class=\"wp-image-9945\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/list2string-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/list2string-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/list2string-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p><strong>Problem<\/strong>: Given a list of elements. How to convert them to a string?<\/p>\n<p><strong>Example<\/strong>: Given the following list of strings.<\/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=\"\">\nlst = ['a', 'b', 'c']<\/pre>\n<p>You want to convert the list of strings to 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=\"\">'abc'<\/pre>\n<p>What&#8217;s the most Pythonic way of converting a list to a string? The answer depends on the nuances.<\/p>\n<p>Here&#8217;s a quick overview before we dive into each of the methods:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/66febeb22d\" width=\"100%\" height=\"450\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code! What&#8217;s the most Pythonic way in your opinion?<\/em><\/p>\n<h2>Method 1: Join List of Strings<\/h2>\n<p>The most straightforward way is to use the <code>string.join(iterable)<\/code> method that concatenates all values in the <code>iterable<\/code> (such as a list) using the separator <code>string<\/code> in between the elements.<\/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 = ['a', 'b', 'c']\ns = ''.join(lst)<\/pre>\n<p>The output is 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=\"\">print(s)\n# abc<\/pre>\n<p>Due to its conciseness and efficiency, this is the most Pythonic way of converting a list of <em>strings <\/em>to a string. However, the join() method expects that you pass a list of strings. If you have a list of non-strings, it will throw an error! <\/p>\n<p><strong>Related article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-join-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Join List [Ultimate Guide]\">The Ultimate Guide to Python Join<\/a><\/p>\n<h2>Method 2: Join List of Non-Strings with Generator Expression<\/h2>\n<p>So, what to do if you want to convert a list of general objects to a string?<\/p>\n<p>The most Pythonic way to <a href=\"https:\/\/blog.finxter.com\/concatenate-lists-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Concatenate Lists in Python? [Interactive Guide]\">concatenate <\/a>a list of objects is the expression <code>''.join(str(x) for x in lst)<\/code> that converts each object to a string using the built-in <code>str(...)<\/code> function in a <a href=\"https:\/\/blog.finxter.com\/how-to-use-generator-expressions-in-python-dictionaries\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Use Generator Expressions in Python Dictionaries\">generator expression<\/a>. You can concatenate the resulting list of strings using the <code>join()<\/code> method on the empty string as a delimiter. The result is a single string value that\u2019s the concatenation of the objects\u2019 string representations.<\/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 = [1, 2, 3]\ns = ''.join(str(x) for x in lst)\nprint(s)\n# 123<\/pre>\n<p>This general method works for all objects (because all objects implement the <code>__str__<\/code> method per default). It&#8217;s the most Pythonic way of converting a list of non-string<\/p>\n<p><strong>Related article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-use-pythons-join-function-on-a-list-of-objects-rather-than-strings\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Use Python\u2019s Join() on a List of Objects (Not Strings)?\">What&#8217;s the most Pythonic way to join a list of objects?<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"What&#039;s The Most Pythonic Way to Concatenate a List of Objects into a String?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/_JDhMYSIDWI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<h2>Method 3: String Concatenation with +<\/h2>\n<p>Just for the sake of completeness, I want to highlight that you can also concatenate all strings in a list by using the + operator. If you have a list with a few objects, this is a viable option:<\/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 = ['a', 'b', 'c']\ns = lst[0] + lst[1] + lst[2]\nprint(s)\n# abc<\/pre>\n<p>This is inefficient because each <code>+<\/code> operator creates a new string. For <code>n<\/code> list elements, you create <code>n-1<\/code> new strings in memory.<\/p>\n<p><strong>Related article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-concatenation\/\" title=\"Daily Python Puzzle: String Concatenation\" target=\"_blank\" rel=\"noreferrer noopener\">The <code>+<\/code> operator for string concatenation.<\/a><\/p>\n<p>This must be slightly modified when concatenating a list of objects to a single string:<\/p>\n<h2>Method 4: String Concatenation with + and str()<\/h2>\n<p>Again, if you have a list of objects, you need to convert each object to a string first:<\/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=\"\"># Method 4: String Concatenation with + and str()\nlst = [1.0, 2.0, 3.0]\ns = str(lst[0]) + str(lst[1]) + str(lst[2])\nprint(s)\n# 1.02.03.0<\/pre>\n<p>This is very tedious and it deserves to be titled the <em>&#8220;least Pythonic way to convert a list to a string&#8221;<\/em>. You should prefer the general <strong>Method 2<\/strong> that&#8217;s not only shorter and more efficient, but also more readable and generally applicable.<\/p>\n<h2>Method 5: Use Map + Join<\/h2>\n<p>The map function allows you to convert each element to a string first. You can then join the strings using the standard string.join() method on the resulting iterable of strings.<\/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 = [1, 2, 'hello', 3.2]\ns = ''.join(map(str, lst))\nprint(s)\n# 12hello3.2<\/pre>\n<p>This works beautifully for list of objects as well and it&#8217;s quite Pythonic. Many Python coders like this functional style&#8212;but I don&#8217;t consider it the most Pythonic one. Python code should be readable. <a href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\" title=\"About Guido\u2019s Article: \u201cFate of Reduce() in Python 3000\u201d\" target=\"_blank\" rel=\"noreferrer noopener\">Guido van Rossum<\/a>, Python&#8217;s creator, tried to avoid functional programming because he didn&#8217;t find it readable compared to <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a> or its generalization &#8220;generator expressions&#8221; (see <strong>Method 2<\/strong>). <\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-encrpytion-ord-function-map-function\/\" title=\"Mastering the Python Map Function [+Video]\" target=\"_blank\" rel=\"noreferrer noopener\">The map() function in Python<\/a><\/p>\n<h2>Method 6: Simple Loop<\/h2>\n<p>Let&#8217;s see what coders who come from another programming language such as Java would do:<\/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 = [1, 2, 'hello', 3.2]\ns = ''\nfor x in lst: s += str(x)\nprint(s)\n# 12hello3.2<\/pre>\n<p>They&#8217;d first create an empty string. Then, they&#8217;d add the string representation of each list element to the string until all list elements are added. <\/p>\n<p>This is highly inefficient because of the repeated creation of new strings and it needs three lines instead of one. As it&#8217;s often the case in Python, you can avoid loops by using Python&#8217;s powerful built-in capabilities.<\/p>\n<p><strong>Related article<\/strong>:<a href=\"https:\/\/blog.finxter.com\/python-vs-go-which-language-you-should-choose\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python vs Go \u2013 Which Language You Should Choose\"> Go vs Python<\/a><\/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>To convert a list lst of strings to a string, use the &#8221;.join(lst) method with an empty separator string between the elements. If you have a list of objects, first convert each element to a string and join the result with the generator expression &#8221;.join(str(x) for x in lst). Problem: Given a list of elements. [&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-114399","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\/114399","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=114399"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114399\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114399"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114399"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114399"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}