Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Remove Empty Lists from a List of Lists in Python?

#1
How to Remove Empty Lists from a List of Lists in Python?

<div><p><strong>Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement <code>[x for x in list if x]</code> to filter the list. </strong></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="How to Remove Empty Lists from a List of Lists in Python?" width="1400" height="788" src="https://www.youtube.com/embed/Fi3zvSaVY8U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>In the following, you’ll learn about the two methods using list comprehension and the filter() function to remove all empty lists from a list of lists. </p>
<p>But before that, feel free to play with the code yourself:</p>
<p> <iframe src="https://trinket.io/embed/python/659a4282bd" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<h2>Method 1: List Comprehension</h2>
<p>How can you remove all empty lists from a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">list of lists</a>? Say, you’ve got a list of lists</p>
<p><code>[[1, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []]</code> </p>
<p>and you want all empty lists removed to obtain the list of lists </p>
<p><code>[[1, 2, 3], [1, 2], [1, 2, 3, 4]]</code>. </p>
<p><strong>Solution</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> <code>[x for x in list if x]</code> to filter the list and remove all lists that are empty. </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], [1, 2], [], [], [], [1, 2, 3, 4], [], []]
print([x for x in lst if x])
# [[1, 2, 3], [1, 2], [1, 2, 3, 4]]</pre>
<p>The condition if <code>x</code> evaluates to <code>False</code> only if the list <code>x</code> is empty. In all other cases, it evaluates to <code>True</code> and the element is included in the new list.</p>
<p>You can visualize the execution flow here by clicking the “Next” button:</p>
<p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=lst%20%3D%20%5B%5B1,%202,%203%5D,%20%5B1,%202%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B1,%202,%203,%204%5D,%20%5B%5D,%20%5B%5D%5D%0Aprint%28%5Bx%20for%20x%20in%20lst%20if%20x%5D%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<h2>Method 2: filter()</h2>
<p>An alternative is to use the <code>filter()</code> function to remove all empty lists from a list of 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, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []]
print(list(filter(lambda x: x, lst)))
</pre>
<p>The <a href="https://blog.finxter.com/how-to-filter-a-list-in-python/">filter()</a> function takes two arguments: </p>
<ul>
<li>the <strong>filter decision function </strong>to check for each element whether it should be included in the filtered iterable (it returns a Boolean value), and </li>
<li>the <strong>iterable </strong>to be filtered.</li>
</ul>
<p>As filter decision function, you use the identity function that just passes the list through. Why does this work? Because only an empty list will be evaluated to <code>False</code>. All other lists will be evaluated to <code>True</code> (and, thus, pass the filtering test). </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/how-to-filter-a-list-in-python/" target="_blank" rel="noreferrer noopener">How to filter a list in Python?</a></li>
<li><a href="https://blog.finxter.com/python-lists-filter-vs-list-comprehension-which-is-faster/">Filter vs List Comprehension (Speed)</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">Lists of Lists</a></li>
</ul>
<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/05/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python zip(): Get Elements from Multiple Lists xSicKxBot 0 918 08-26-2023, 01:28 AM
Last Post: xSicKxBot
  [Tut] List Comprehension in Python xSicKxBot 0 869 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 841 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 670 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 781 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 646 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 659 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Dictionary of Lists to DataFrame – Python Conversion xSicKxBot 0 692 04-17-2023, 03:46 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 729 04-11-2023, 04:15 AM
Last Post: xSicKxBot
  [Tut] [Fixed] Sendy Loading Lists Not Working (Loads Forever) xSicKxBot 0 637 02-14-2023, 08:12 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016