[Tut] Convert Tuple to List | The Most Pythonic Way - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Convert Tuple to List | The Most Pythonic Way (/thread-95865.html) |
[Tut] Convert Tuple to List | The Most Pythonic Way - xSicKxBot - 06-24-2020 Convert Tuple to List | 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 tuple to a list is Python’s built-in <code>list(tuple)</code> function. You can pass any iterable (such as a tuple, another list, or a set) as an argument into this so-called <em>constructor function</em> and it returns a new list 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 Tuple to List | The Most Pythonic Way" width="1400" height="788" src="https://www.youtube.com/embed/4ymuQCX-wLI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p><em>Converting a tuple to a list 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 tuple of elements. Create a new list with the same elements—thereby converting the tuple to a list.</p> <p><strong>Example</strong>: You have 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="">t = (1, 2, 3)</pre> <p>You want to create a new <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list data structure</a> 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 tuple to a list—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/dcf132285d" width="100%" height="700" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p> <p><em><strong>Exercise</strong>: Run the code. Skim over each method—which one do you like most? Do you understand each of them?</em></p> <p>Let’s dive into the six methods.</p> <h2>Method 1: List Constructor</h2> <p>The simplest, most straightforward, and most readable way to convert a tuple to a list is Python’s built-in <code>list(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>, a 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/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="(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=""> # Method 1: list() constructor t = (1, 2, 3) lst = list(t) print(lst) # [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 tuple to a list is all you need. But what if you want to convert multiple tuples to a single list?</p> <h2>Method 2: Unpacking</h2> <p>There’s an alternative that works for <strong>one or more tuples</strong> to convert one or more tuples into a list. 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 tuple (or list). The operator will “unpack” all elements into an outer structure—for example, into an argument lists or into an enclosing container type such as a list or a tuple.</p> <p>Here’s how it works to unpack all elements of a tuple into an enclosing list—thereby converting the original tuple to a new 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=""># Method 2: Unpacking t = (1, 2, 3) lst = [*t] print(lst) # [1, 2, 3]</pre> <p>You unpack all elements in the tuple <code>t</code> into the outer structure <code>[*t]</code>. The strength of this approach is—despite being even conciser than the standard <code>list(...)</code> function—that you can unpack multiple values into it!</p> <h2>Method 3: Unpacking to Convert Multiple Tuples to a Single List</h2> <p>Let’s have a look at how you’d create a list from multiple tuples:</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=""># Method 3: Unpacking Multiple Tuples t1 = (1, 2, 3) t2 = (4, 5, 6) lst = [*t1, *t2] print(lst) # [1, 2, 3, 4, 5, 6]</pre> <p>The expression <code>[*t1, *t2]</code> unpacks all elements in tuples <code>t1</code> and <code>t2</code> into the outer list. This allows you to convert multiple tuples to a single list.</p> <h2>Method 4: Generator Expression to Convert Multiple Tuples to List</h2> <p>If you have multiple tuples 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> (or list of tuples) and you want to convert them to a single list, 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 tuples and over all elements of each inner tuple. Then, you place each of those elements into the list 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=""># Method 4: Generator Expression ts = ((1, 2), (3, 4), (5, 6, 7)) lst = [x for t in ts for x in t] print(lst) # [1, 2, 3, 4, 5, 6, 7]</pre> <p>This is the most Pythonic way to convert a list of tuples (or tuple of tuples) 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=""># Method 5: Generator Expression + Unpacking t = ((1, 2), (3, 4), (5, 6, 7)) lst = [*(x for t in ts for x in t)] print(lst) # [1, 2, 3, 4, 5, 6, 7]</pre> <p>Rather than using the <code>list(...)</code> function to convert the generator expression to a list, you use the <code>[...]</code> helper structure to indicate that it’s a list you want—and unpack all elements from the generator expression into the list. 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> <h2>Method 6: Simple For Loop</h2> <p>Let’s end this article by showing the simple thing—using a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">for loop</a>. Doing simple things is an excellent idea in coding. And, while the problem is more elegantly solved in <strong>Method 1</strong> (using the <code>list()</code> constructor), using a simple loop to fill an initially empty list is the default strategy.</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=""># Method 6: Simple For Loop t = (1, 2, 3, 4) lst = [] for x in t: lst.append(x) print(lst) # [1, 2, 3, 4]</pre> <p>To understand how the code works, you can visualize its execution in the interactive memory visualizer:</p> <p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=%23%20Method%206%3A%20Simple%20For%20Loop%0At%20%3D%20%281,%202,%203,%204%29%0Alst%20%3D%20%5B%5D%0Afor%20x%20in%20t%3A%0A%20%20%20%20lst.append%28x%29%0Aprint%28lst%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p> <p><em><strong>Exercise</strong>: How often is the loop condition checked?</em></p> <p>You will see such a simple conversion method in code bases of Python beginners and programmers who switch to Python <a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" title="Python vs Go – Which Language You Should Choose" target="_blank" rel="noreferrer noopener">coming from other programming languages</a> such as Java or C++. It’s readable but it lacks conciseness. </p> <p>I hope you liked the article! Please find related articles here:</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>If you want to boost your Python skills, I’ve created an online academy that’s entirely based on email (and it’s free).</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/23/convert-tuple-to-list-the-most-pythonic-way/ |