Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Convert List to Tuple | The Most Pythonic Way

#1
Convert List to Tuple | The Most Pythonic Way

<div><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’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>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe 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>
</div>
</figure>
<p><em>Converting a list to a tuple seems trivial, I know. But keep reading and I’ll show you surprising ways of handling this problem. I guarantee that you’ll learn a lot of valuable things from the 3-5 minutes you’ll spend reading this tutorial! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></p>
<p><strong>Problem</strong>: Given a list of elements. Create a new tuple with the same elements—thereby converting the list to a tuple.</p>
<p><strong>Example</strong>: You have the following list.</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="">lst = [1, 2, 3]</pre>
<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’s Invention Sped Up a Certain Task Significantly?">data structur</a>e that contains the same integer elements:</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)</pre>
<p>Let’s have a look at the different ways to convert a list to a tuple—and discuss which is the most Pythonic way in which circumstance.</p>
<p>You can get a quick overview in the following interactive code shell. Explanations for each method follow after that:</p>
<p> <iframe src="https://trinket.io/embed/python/dc9e315394" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code. Skim over each method—does any of them confuse you?</em></p>
<h2>Method 1: Tuple Constructor</h2>
<p>The simplest, most straightforward, and most readable way to convert a list to a tuple is Python’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 – 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>
<figure class="wp-block-image is-resized"><img 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/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p>Here’s an example:</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="">lst = [1, 2, 3]
t = tuple(lst)</pre>
<p>The result is the following tuple:</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(t)
# (1, 2, 3)</pre>
<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’t. 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 – A Helpful Illustrated Guide to Nested Lists in Python">multiple lists</a> to a tuple?</p>
<h2>Method 2: Unpacking</h2>
<p>There’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’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>
<p>The asterisk operator <code>*</code> is also called “star operator” and you can use it as a prefix on any list. The operator will “unpack” all elements of the list into the outer structure—so make sure you call it only within argument lists or within an enclosing container type such as a list or a tuple.</p>
<p>Here’s how it works to unpack all elements of a list into an enclosing tuple—thereby converting the original list to a new tuple.</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="">t = (*lst,)
print(t)
# (1, 2, 3)</pre>
<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’s a tuple and not the parentheses of a simple expression. If you’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’s no outer container data structure that “catches” the unpacked elements. </p>
<p>The strength of this approach is—despite being even conciser than the standard <code>tuple(...)</code> function—that you can unpack multiple values into it!</p>
<h2>Method 3: Unpacking to Convert Multiple Lists to a Single Tuple</h2>
<p>Let’s have a look at how you’d create a tuple from multiple lists:</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="">lst_1 = [1, 2, 3]
lst_2 = [4, 5, 6]
t = (*lst_1, *lst_2)
print(t)
# (1, 2, 3, 4, 5, 6)</pre>
<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>
<h2>Method 4: Generator Expression to Convert Multiple Lists to Tuple</h2>
<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>
<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]]
t = tuple(x for l in lst for x in l)
print(t)
# (1, 2, 3, 4, 5, 6, 7)</pre>
<p>This is the most Pythonic way to convert a list of lists to a tuple. It’s short and efficient and readable. You don’t create any helper data structure that takes space in memory. </p>
<p><em>But what if you want to save a few more characters?</em></p>
<h2>Method 5: Generator Expression + Unpacking</h2>
<p>Okay, you shouldn’t do this last method using the asterisk operator—it’s unreadable—but I couldn’t help including it here:</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="">lst = [[1, 2], [3, 4], [5, 6, 7]]
t = (*(x for l in lst for x in l),)
print(t)
# (1, 2, 3, 4, 5, 6, 7)</pre>
<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’s a tuple you want—and unpack all elements from the generator expression into the tuple. Sure, it’s not very readable—but you could see such a thing in practice (if pro coders want to show off their skills ;)). </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-copy/" target="_blank">List copy</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">List complete guide</a></li>
<li><a href="https://blog.finxter.com/convert-list-to-tuple/" target="_blank" rel="noreferrer noopener">Convert list to tuple</a></li>
</ul>
<p>I hope you liked the article! </p>
<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>
<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/...honic-way/
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016