Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert Tuple of Tuples to List of Lists in Python?

#1
How to Convert Tuple of Tuples to List of Lists in Python?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;388975&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Given a tuple of <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuples</a> such as <code>((1, 2), (3, 4))</code>. How to convert it to a <a href="https://blog.finxter.com/python-list-of-lists/" data-type="post" data-id="7890" target="_blank" rel="noreferrer noopener">list of lists</a> such as <code>[[1, 2], [3, 4]]</code>? </p>
<p><strong>If you’re in a hurry, here’s the most Pythonic way to convert a nested tuple to a nested list: </strong></p>
<p class="has-global-color-8-background-color has-background">The <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank">list comprehension</a></strong> statement <code>[list(x) for x in tuples]</code> converts each tuple in <code>tuples</code> to a list and stores the results in a list of lists.</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/05/list_of_lists_to_tuple_of_tuples-1024x576.jpg" alt="" class="wp-image-388997" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/list_of_lists_to_tuple_of_tuples-1024x576.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...tuples.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>But there’s more to it! Studying the different methods to achieve the same goal will make you a better coder. </p>
<p>So keep reading!</p>
<h2>Method 1: List Comprehension + list()</h2>
<p class="has-global-color-8-background-color has-background">The recommended way to convert a tuple of tuples to a list of lists is using <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> in combination with the built-in <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502" target="_blank">list()</a></code> function like so: <code>[list(x) for x in tuples]</code>.</p>
<p>Here’s a concrete example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1, 2), (3, 4), (5, 6))
lists = [list(x) for x in tuples] print(lists)
# [[1, 2], [3, 4], [5, 6]]
</pre>
<p>Try It Yourself:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/0c1caeca9b" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p>This approach is simple and effective. List comprehension defines how to convert each tuple (<code>x</code> in the example) to a new list element. As each list element is a new list, you use the <a rel="noreferrer noopener" href="https://blog.finxter.com/convert-tuple-to-list/" target="_blank">constructor <code>list(x)</code></a> to create a new list from the tuple <code>x</code>.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python list() — A Simple Guide" width="780" height="439" src="https://www.youtube.com/embed/zt19-2eW-hY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h3>Example Three Elements per Tuple</h3>
<p>If you have three elements per tuple, you can use the same approach with the conversion:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1, 2, 1), (3, 4, 3), (5, 6, 5))
lists = [list(x) for x in tuples]
print(lists)
</pre>
<p>You can see the execution flow in the following interactive visualization (just click the “Next” button to see what’s happening in the code):</p>
<p> <iframe loading="lazy" src="https://pythontutor.com/iframe-embed.html#code=tuples%20%3D%20%28%281,%202,%201%29,%20%283,%204,%203%29,%20%285,%206,%205%29%29%0Alists%20%3D%20%5Blist%28x%29%20for%20x%20in%20tuples%5D%0Aprint%28lists%29%0A&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500" frameborder="0"> </iframe> </p>
<h3>Example Varying Number of Tuple Elements</h3>
<p>And if you have a varying <a href="https://blog.finxter.com/python-len/" data-type="post" data-id="22386" target="_blank" rel="noreferrer noopener">number of elements</a> per tuple, this approach still works beautifully:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1,), (3, 3), (5, 6, 5))
lists = [list(x) for x in tuples] print(lists)
# [[1], [3, 3], [5, 6, 5]]</pre>
<p>You see that an approach with list comprehension is the best way to convert a tuple of tuples to a list of lists. </p>
<p>But are there any alternatives?</p>
<h2>Method 2: Use Asterisk and List Comprehension</h2>
<p class="has-global-color-8-background-color has-background">A variant of the recommended way to convert a tuple of tuples to a list of lists is using <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> in combination with the unpacking asterisk operator <code>*</code> like so: <code>[[*x] for x in tuples]</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1,), (3, 3), (5, 6, 5))
lists = [[*x] for x in tuples] print(lists)
# [[1], [3, 3], [5, 6, 5]]</pre>
<p>The unpacking operator <code>[*x]</code> takes all tuple elements from <code>x</code> and “unpacks” them in the outer list container <code>[...]</code>. For example, the expression <code>[*(5, 6, 5)]</code> yields the list <code>[5, 6, 5]</code>. </p>
<p>Let’s have a look at a completely different approach to solve this problem:</p>
<h2>Method 3: Map Function + list()</h2>
<p>Use the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank">map fu</a><a href="https://blog.finxter.com/python-map/" data-type="post" data-id="242" target="_blank" rel="noreferrer noopener">n</a><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank">ction</a> that applies a specified function on each element of an iterable. </p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Side Note</strong>: Guido van Rossum, the creator of Python, didn’t like the <code>map()</code> function as it’s less readable and less efficient than the list comprehension version (Method 1 in this tutorial). <a rel="noreferrer noopener" href="https://blog.finxter.com/about-guidos-fate-of-reduce-in-python-3000/" target="_blank">You can read about a detailed discussion on how exactly he argued on my blog article.</a></p>
<p>So, without further ado, here’s how you can convert a tuple of tuples into a list ot lists using the <code>map()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1,), (2, 3, 4), (5, 6, 7, 8))
lists = list(map(list, tuples)) print(lists)
# [[1], [2, 3, 4], [5, 6, 7, 8]]
</pre>
<p>Try it yourself:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/e4c1895d61" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p>Video tutorial on the <code>map()</code> function:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Mastering the Python Map Function [+Video]" width="780" height="439" src="https://www.youtube.com/embed/tqph6mWC3m8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p>The first argument of the <code>map()</code> function is the <code>list</code> function name. </p>
<p>This <code><a href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502" target="_blank" rel="noreferrer noopener">list()</a></code> function converts each element on the given <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterable</a> <code>tuples</code> (the second argument) into a list. </p>
<p>The result of the <code>map()</code> function is an iterable too, so you need to convert it to a list before <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">printing</a> it to the shell because the default string <a href="https://blog.finxter.com/python-repr-function/" data-type="post" data-id="23817" target="_blank" rel="noreferrer noopener">representation</a> of an iterable is not human-readable.</p>
<h2>Method 4: Simple For Loop with append() and list()</h2>
<p class="has-global-color-8-background-color has-background">To convert a tuple of tuples to a list of lists, a simple three-liner is to first initialize an empty “outer” list and store it in a variable. Then iterate over all tuples using a simple <code><a href="https://blog.finxter.com/powershell-loops-a-simple-guide-with-video/" data-type="post" data-id="67400" target="_blank" rel="noreferrer noopener">for</a></code> loop and convert each separately to a list and append each result to the outer list variable using the <code>list.append()</code> builtin method in the loop body. </p>
<p>The following example does exactly that:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuples = ((1,), (2, 3, 4), (5, 6, 7, 8)) lists = []
for t in tuples: lists.append(list(t)) print(lists)
# [[1], [2, 3, 4], [5, 6, 7, 8]]
</pre>
</p>
<h2>Related Video Tutorial</h2>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Convert List of Lists to List of Tuples in Python? (And Back)" width="780" height="439" src="https://www.youtube.com/embed/46qIUD0jN6w?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Related Conversion Articles</h2>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-list-of-lists-to-list-of-tuples-in-python/" target="_blank">How to Convert a List of Lists to a List of Tuples</a></li>
<li><a href="https://blog.finxter.com/how-to-convert-list-of-lists-to-a-pandas-dataframe/">How to Convert a List of Lists to a Pandas Dataframe</a></li>
<li><a href="https://blog.finxter.com/how-to-convert-list-of-lists-to-numpy-array/"></a><a href="https://blog.finxter.com/how-to-convert-list-of-lists-to-a-pandas-dataframe/">How to Convert a List of Lists to a NumPy Array</a></li>
<li><a href="https://blog.finxter.com/how-to-convert-a-list-of-list-to-a-dictionary-in-python/">How to Convert a List of Lists to a Dictionary in Python</a></li>
</ul>
<h2>Where to Go From Here?</h2>
<p>Enough theory. Let’s get some practice!</p>
<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>
<p>To become more successful in coding, solve more real problems for real people. 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>You build high-value coding skills by working on practical coding projects!</strong></p>
<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>If you just want to learn about the freelancing opportunity, feel free to watch 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 learn 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></p>
</div>


https://www.sickgaming.net/blog/2022/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016