{"id":114442,"date":"2020-06-21T15:02:56","date_gmt":"2020-06-21T15:02:56","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9960"},"modified":"2020-06-21T15:02:56","modified_gmt":"2020-06-21T15:02:56","slug":"convert-list-to-tuple-the-most-pythonic-way","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/21\/convert-list-to-tuple-the-most-pythonic-way\/","title":{"rendered":"Convert List to Tuple | The Most Pythonic Way"},"content":{"rendered":"<p class=\"has-black-color has-luminous-vivid-amber-background-color has-text-color has-background\"><strong>Answer<\/strong>: The simplest, most straightforward, and most readable way to convert a list to a tuple is Python&#8217;s built-in <code>tuple(list)<\/code> function. You can pass any iterable (such as a list, another tuple, or a set) as an argument into this so-called <em>constructor function<\/em> and it returns a new tuple data structure that contains all elements of the iterable.<\/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=\"Convert List to Tuple | The Most Pythonic Way\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/C9xc8lZ_058?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><em>Converting a list to a tuple seems trivial, I know. But keep reading and I&#8217;ll show you surprising ways of handling this problem. I guarantee that you&#8217;ll learn a lot of valuable things from the 3-5 minutes you&#8217;ll spend reading this tutorial! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/em><\/p>\n<p><strong>Problem<\/strong>: Given a list of elements. Create a new tuple with the same elements&#8212;thereby converting the list to a tuple.<\/p>\n<p><strong>Example<\/strong>: You have the following list.<\/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]<\/pre>\n<p>You want to create a new tuple <a href=\"https:\/\/blog.finxter.com\/what-data-structure-or-algorithms-invention-sped-up-a-certain-task-significantly\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"What Data Structure or Algorithm\u2019s Invention Sped Up a Certain Task Significantly?\">data structur<\/a>e that contains the same integer 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=\"\">(1, 2, 3)<\/pre>\n<p>Let&#8217;s have a look at the different ways to convert a list to a tuple&#8212;and discuss which is the most Pythonic way in which circumstance.<\/p>\n<p>You can get a quick overview in the following interactive code shell. Explanations for each method follow after that:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/dc9e315394\" width=\"100%\" height=\"600\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code. Skim over each method&#8212;does any of them confuse you?<\/em><\/p>\n<h2>Method 1: Tuple Constructor<\/h2>\n<p>The simplest, most straightforward, and most readable way to convert a list to a tuple is Python&#8217;s built-in <code>tuple(iterable)<\/code> function. You can pass any iterable (such as a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" title=\"The Ultimate Guide to Python Lists\" target=\"_blank\" rel=\"noreferrer noopener\">list<\/a>, another tuple, or a <a href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Sets \u2013 with Harry Potter Examples\">set<\/a>) as an argument into this so-called <em>constructor function<\/em> and it returns a new tuple data structure that contains all elements of the iterable. <\/p>\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/list_to_tuple-1024x576.jpg\" alt=\"Convert List to Tuple using tuple()\" class=\"wp-image-7866\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/list_to_tuple-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/list_to_tuple-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/list_to_tuple-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p>Here&#8217;s an 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=\"\">lst = [1, 2, 3]\nt = tuple(lst)<\/pre>\n<p>The result is the following tuple:<\/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(t)\n# (1, 2, 3)<\/pre>\n<p>This is the most Pythonic way if a <a href=\"https:\/\/blog.finxter.com\/join-list-of-lists\/\" title=\"How to Join a List of Lists? You Don\u2019t. You Flatten It!\" target=\"_blank\" rel=\"noreferrer noopener\">flat <\/a>conversion of a single list to a tuple is all you need. But what if you want to convert <a href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python List of Lists \u2013 A Helpful Illustrated Guide to Nested Lists in Python\">multiple lists<\/a> to a tuple?<\/p>\n<h2>Method 2: Unpacking<\/h2>\n<p>There&#8217;s an alternative that works for <strong>one or more lists<\/strong>. In other words, you can use this general method to convert one or more lists into a tuple. This method is equally efficient and it takes less characters than <strong>Method 1<\/strong> (at the costs of <a href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">readability <\/a>for beginner coders). Sounds interesting? Let&#8217;s dive into <a href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"What is the Asterisk \/ Star Operator (*) in Python?\">unpacking and the asterisk operator<\/a>!<\/p>\n<p>The asterisk operator <code>*<\/code> is also called &#8220;star operator&#8221; and you can use it as a prefix on any list. The operator will &#8220;unpack&#8221; all elements of the list into the outer structure&#8212;so make sure you call it only within argument lists or within an enclosing container type such as a list or a tuple.<\/p>\n<p>Here&#8217;s how it works to unpack all elements of a list into an enclosing tuple&#8212;thereby converting the original list to a new tuple.<\/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=\"\">t = (*lst,)\nprint(t)\n# (1, 2, 3)<\/pre>\n<p>You unpack all elements in the <code>lst<\/code> into the outer structure <code>(<code>*lst<\/code>,)<\/code>. The outer parentheses with the comma indicate that it&#8217;s a tuple and not the parentheses of a simple expression. If you&#8217;d forget to add the comma, Python would interpret the expression <code>(*lst)<\/code> as being a simple precedence relation and it would throw an error because there&#8217;s no outer container data structure that &#8220;catches&#8221; the unpacked elements. <\/p>\n<p>The strength of this approach is&#8212;despite being even conciser than the standard <code>tuple(...)<\/code> function&#8212;that you can unpack multiple values into it!<\/p>\n<h2>Method 3: Unpacking to Convert Multiple Lists to a Single Tuple<\/h2>\n<p>Let&#8217;s have a look at how you&#8217;d create a tuple from multiple lists:<\/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 = [1, 2, 3]\nlst_2 = [4, 5, 6]\nt = (*lst_1, *lst_2)\nprint(t)\n# (1, 2, 3, 4, 5, 6)<\/pre>\n<p>The expression <code>(*lst_1, *lst_2)<\/code> unpacks all elements in <code>lst_1<\/code> and <code>lst_2<\/code> into the outer tuple structure. This allows you to convert multiple lists to a single tuple.<\/p>\n<h2>Method 4: Generator Expression to Convert Multiple Lists to Tuple<\/h2>\n<p>If you have multiple lists stored in a <a href=\"https:\/\/blog.finxter.com\/how-to-merge-lists-into-a-list-of-tuples\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Merge Lists into a List of Tuples? [6 Pythonic Ways]\">list of lists<\/a> and you want to convert them to a single tuple, you can use a short <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> statement to go over all inner lists and over all elements of each inner list. Then, you place each of those elements into the tuple structure:<\/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, 4], [5, 6, 7]]\nt = tuple(x for l in lst for x in l)\nprint(t)\n# (1, 2, 3, 4, 5, 6, 7)<\/pre>\n<p>This is the most Pythonic way to convert a list of lists to a tuple. It&#8217;s short and efficient and readable. You don&#8217;t create any helper data structure that takes space in memory. <\/p>\n<p><em>But what if you want to save a few more characters?<\/em><\/p>\n<h2>Method 5: Generator Expression + Unpacking<\/h2>\n<p>Okay, you shouldn&#8217;t do this last method using the asterisk operator&#8212;it&#8217;s unreadable&#8212;but I couldn&#8217;t help including it here:<\/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, 4], [5, 6, 7]]\nt = (*(x for l in lst for x in l),)\nprint(t)\n# (1, 2, 3, 4, 5, 6, 7)<\/pre>\n<p>Rather than using the <code>tuple(...)<\/code> function to convert the generator expression to a tuple, you use the <code>(...,)<\/code> helper structure to indicate that it&#8217;s a tuple you want&#8212;and unpack all elements from the generator expression into the tuple. Sure, it&#8217;s not very readable&#8212;but you could see such a thing in practice (if pro coders want to show off their skills ;)). <\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-copy\/\" target=\"_blank\">List copy<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List complete guide<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/convert-list-to-tuple\/\" target=\"_blank\" rel=\"noreferrer noopener\">Convert list to tuple<\/a><\/li>\n<\/ul>\n<p>I hope you liked the article! <\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Subscribe\">Feel free to join our large community of ambitious Python coders and download your free Python resources (PDF cheat sheets). <\/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>Answer: The simplest, most straightforward, and most readable way to convert a list to a tuple is Python&#8217;s built-in tuple(list) function. You can pass any iterable (such as a list, another tuple, or a set) as an argument into this so-called constructor function and it returns a new tuple data structure that contains all 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-114442","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\/114442","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=114442"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114442\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114442"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114442"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114442"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}