[Tut] How to Join a List of Lists? You Don’t. You Flatten It! - 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] How to Join a List of Lists? You Don’t. You Flatten It! (/thread-95359.html) |
[Tut] How to Join a List of Lists? You Don’t. You Flatten It! - xSicKxBot - 06-02-2020 How to Join a List of Lists? You Don’t. You Flatten It! <div><p class="has-background has-luminous-vivid-amber-background-color"><strong>Short answer: To flatten your list of list <code>lst</code>, use the nested list comprehension <code>[x for l in lst for x in l]</code> to iterate over all nested lists (<code>for l in lst</code>) and over all their elements (<code>for x in l</code>). Each element <code>x</code>, you just place in the outer list, unchanged.</strong></p> <p>When browsing <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/716477/join-list-of-lists-in-python" target="_blank">StackOverflow</a>, I stumble upon this question from time to time: “<em><strong>How to Join a List of Lists?</strong></em>“. My first thought is that the asking person is referring to the<a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener"> join() function</a> that converts an iterable (such as a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list</a>) to a string by <a href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/" target="_blank" rel="noreferrer noopener">concatenating </a>its elements. </p> <p>But nothing can be further from the truth! The question is usually about “flattening” the list: to transform a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">nested list of lists</a> such as <code>[[1, 2, 3], [4, 5, 6]]</code> to a flat list <code>[1, 2, 3, 4, 5, 6]</code>. So, the real question is:</p> <h2>How to Flatten a List of Lists in Python?</h2> <p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener">list of lists</a>. How to flatten the list of lists by getting rid of the inner lists—and keeping their elements?</p> <p><strong>Example</strong>: You want to transform a given list into a flat list like 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 = [[2, 2], [4], [1, 2, 3, 4], [1, 2, 3]] # ... Flatten the list here ... print(lst) # [2, 2, 4, 1, 2, 3, 4, 1, 2, 3]</pre> <figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/04/flatten-1024x576.jpg" alt="Flatten a List of Lists with List Comprehension" class="wp-image-8068" width="512" height="288" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/flatten-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/04/flatten-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/04/flatten-768x432.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></figure> <p><strong>Solution</strong>: Use a nested <a rel="noreferrer noopener" href="https://blog.finxter.com/which-is-faster-list-comprehension-or-map-function-in-python/" target="_blank">list comprehension</a> statement <code>[x for l in lst for x in l]</code> to flatten the 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 = [[2, 2], [4], [1, 2, 3, 4], [1, 2, 3]] # ... Flatten the list here ... lst = [x for l in lst for x in l] print(lst) # [2, 2, 4, 1, 2, 3, 4, 1, 2, 3]</pre> <p><strong>Explanation</strong>: In the nested list comprehension statement <code>[x for l in lst for x in l]</code>, you first iterate over all lists in the list of lists (<code>for l in lst</code>). Then, you iterate over all elements in the current list (<code>for x in l</code>). This element, you just place in the outer list, unchanged, by using it in the “expression” part of the list comprehension statement <code>[<strong>x</strong> for l in lst for x in l]</code>. </p> <p><strong>Try It Yourself</strong>: You can execute this code snippet yourself in our interactive Python shell. Just click “Run” and test the output of this code. </p> <p> <iframe src="https://repl.it/@finxter/flattenlistoflist?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="700px" frameborder="no"></iframe> </p> <p><em><strong>Exercise</strong>: How to flatten a three-dimensional list (= a list of lists of lists)? Try it in the shell!</em></p> <h2>Video: List Comprehension Python List of Lists</h2> <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="List Comprehension Python List of Lists" width="1400" height="788" src="https://www.youtube.com/embed/3CGmDLOiqR4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>Watch the video to learn three ways how to apply <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> to a list of lists:</p> <ul> <li>to <strong>flatten </strong>a list of lists,</li> <li>to <strong>create </strong>a list of lists, and</li> <li>to <strong>iterate over</strong> a list of lists.</li> </ul> <p>Well, if you really want to learn how to <code>join()</code> a list in Python, visit <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">this detailed tutorial on the Finxter blog</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/01/how-to-join-a-list-of-lists-you-dont-you-flatten-it/ |