Create an account


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

#1
How to Convert List of Lists to Tuple of Tuples 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;389161&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 <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">list of lists</a> such as <code>[[1, 2], [3, 4]]</code>. How to convert it to a tuple of <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">tuples</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 list to a nested tuple: </strong></p>
<p class="has-global-color-8-background-color has-background">Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/understanding-generators-in-python/" data-type="post" data-id="33873" target="_blank">generator expression</a> with the built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-tuple/" data-type="URL" data-id="https://blog.finxter.com/python-tuple/" target="_blank"><code>tuple()</code></a> function to convert a list of lists to a tuple of tuples like so: <code><code>tuple(tuple(x) for x in my_list)</code></code>.</p>
<p>Here’s a graphic on how to <a href="https://blog.finxter.com/how-to-convert-tuple-of-tuples-to-list-of-lists-in-python/" data-type="post" data-id="388975" target="_blank" rel="noreferrer noopener">convert back and forth</a> between nested list and nested tuples:</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="Convert List of Lists to Tuple of Tuples in Python" 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. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d1-200d-1f4bb.png" alt="?‍?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>So keep reading!</p>
<h2>Method 1: Tuple Comprehension + tuple()</h2>
<p class="has-global-color-8-background-color has-background">The recommended way to convert a list of lists to a tuple of tuples is using <a rel="noreferrer noopener" href="https://blog.finxter.com/understanding-generators-in-python/" data-type="post" data-id="33873" target="_blank">generator expression</a> in combination with the built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-tuple/" data-type="URL" data-id="https://blog.finxter.com/python-tuple/" target="_blank"><code>tuple()</code></a> function like so: <code><code>tuple(tuple(x) for x in my_list)</code></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="">lists = [[1, 2], [3, 4], [5, 6]]
tuples = tuple(tuple(x) for x in lists) print(tuples)
# ((1, 2), (3, 4), (5, 6))
</pre>
<p>Try It Yourself:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/98fd39ea7a" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p>This approach is simple and effective. The generator expression defines how to convert each inner list (<code>x</code> in the example) to a new tuple element. </p>
<p>You use the <a href="https://blog.finxter.com/convert-list-to-tuple/" data-type="post" data-id="7862" target="_blank" rel="noreferrer noopener">constructor <code>tuple(x)</code></a> to create a new tuple from the list <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 tuple() — A Simple Guide" width="780" height="439" src="https://www.youtube.com/embed/ViJ1E-52hq4?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 list, 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="">lists = [[1, 2, 1], [3, 4, 3], [5, 6, 5]]
tuples = tuple(tuple(x) for x in lists) print(tuples)
# ((1, 2, 1), (3, 4, 3), (5, 6, 5))
</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" width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=lists%20%3D%20%5B%5B1,%202,%201%5D,%20%5B3,%204,%203%5D,%20%5B5,%206,%205%5D%5D%0Atuples%20%3D%20tuple%28tuple%28x%29%20for%20x%20in%20lists%29%0A%0Aprint%28tuples%29%0A%23%20%28%281,%202,%201%29,%20%283,%204,%203%29,%20%285,%206,%205%29%29%0A&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<h3>Example Varying Number of List Elements</h3>
<p>And if you have a varying <a rel="noreferrer noopener" href="https://blog.finxter.com/python-len/" data-type="post" data-id="22386" target="_blank">number of elements</a> per list, 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="">lists = [[1], [2, 4, 3], [6, 5]]
tuples = tuple(tuple(x) for x in lists) print(tuples)
# ((1,), (2, 4, 3), (6, 5))</pre>
<p>You see that an approach with generator expression is the best way to convert a list of lists to a tuple of tuples.</p>
<p>But are there any alternatives? Let’s have a look at a completely different approach to solve this problem:</p>
<h2>Method 2: Map Function + list()</h2>
<p>Use the <a href="https://blog.finxter.com/python-map/" data-type="post" data-id="242" target="_blank" rel="noreferrer noopener">map function</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 generator expression 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 list of lists into a tuple of tuples 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="">lists = [[1], [2, 4, 3], [6, 5]]
tuples = tuple(map(tuple, lists)) print(tuples)
# ((1,), (2, 4, 3), (6, 5))</pre>
<p>Try it yourself:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/988e6b062f" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></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>tuple</code> function name. </p>
<p>This <a rel="noreferrer noopener" href="https://blog.finxter.com/python-tuple/" data-type="URL" data-id="https://blog.finxter.com/python-tuple/" target="_blank"><code>tuple()</code></a> function converts each element on the given <a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank">iterable</a> <code>lists</code> (the second argument) into a tuple. </p>
<p>The result of the <code>map()</code> function is an iterable too, so you need to convert it to a tuple before <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">printing</a> it to the shell because the default string <a rel="noreferrer noopener" href="https://blog.finxter.com/python-repr-function/" data-type="post" data-id="23817" target="_blank">representation</a> of an iterable is not human-readable.</p>
<h2>Method 3: Simple For Loop with append() and tuple()</h2>
<p class="has-global-color-8-background-color has-background">To convert a list of lists to a tuple of tuples, first initialize an empty “outer” list and store it in a variable. </p>
<p class="has-global-color-8-background-color has-background">Then iterate over all lists using a simple <code><a rel="noreferrer noopener" href="https://blog.finxter.com/powershell-loops-a-simple-guide-with-video/" data-type="post" data-id="67400" target="_blank">for</a></code> loop and <a href="https://blog.finxter.com/convert-list-to-tuple-2/" data-type="post" data-id="9960" target="_blank" rel="noreferrer noopener">convert</a> each separately to a tuple. </p>
<p class="has-global-color-8-background-color has-background">Next, append each result to the outer list variable using the <code><a href="https://blog.finxter.com/python-list-append/" data-type="post" data-id="6605" target="_blank" rel="noreferrer noopener">list.append()</a></code> builtin method in the loop body. </p>
<p class="has-global-color-8-background-color has-background">Finally, convert the list of tuples to a list tuple of tuples using the <code><a href="https://blog.finxter.com/python-tuple/" data-type="post" data-id="21575" target="_blank" rel="noreferrer noopener">tuple()</a></code> function.</p>
<p>The following example does exactly that:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lists = [[1], [2, 4, 3], [6, 5]] tmp = []
for t in lists: tmp.append(tuple(t))
tuples = tuple(tmp) print(tuples)
# ((1,), (2, 4, 3), (6, 5))</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>
<li><a href="https://blog.finxter.com/how-to-convert-tuple-of-tuples-to-list-of-lists-in-python/" data-type="post" data-id="388975" target="_blank" rel="noreferrer noopener">How to Convert a Tuple of Tuples to a List of Lists 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:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016