{"id":112686,"date":"2020-05-09T09:03:15","date_gmt":"2020-05-09T09:03:15","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=8359"},"modified":"2020-05-09T09:03:15","modified_gmt":"2020-05-09T09:03:15","slug":"how-to-filter-a-list-of-lists-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/05\/09\/how-to-filter-a-list-of-lists-in-python\/","title":{"rendered":"How to Filter a List of Lists in Python?"},"content":{"rendered":"<p><strong>Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement <code>[x for x in list if condition(x)]<\/code> and replace <code>condition(x)<\/code> with your filtering condition that returns <code>True<\/code> to include inner list <code>x<\/code>, and <code>False<\/code> otherwise. <\/strong><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"How to Filter a List in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/3nG4TLkqzf8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Lists belong to the most important data structures in Python&#8212;every master coder knows them by heart! Surprisingly, even intermediate coders don&#8217;t know the best way to <a href=\"https:\/\/blog.finxter.com\/how-to-filter-a-list-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">filter a list<\/a>&#8212;let alone a list of lists in Python. This tutorial shows you how to do the latter!<\/p>\n<p><strong>Problem<\/strong>: Say, you&#8217;ve got a list of lists. You want to filter the list of lists so that only those inner lists remain that satisfy a certain condition. The condition is a function of the inner list&#8212;such as the average or sum of the inner list elements.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/filter-1024x576.jpg\" alt=\"\" class=\"wp-image-8362\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/filter-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/filter-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/05\/filter-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p><strong>Example<\/strong>: Given the following list of lists with weekly temperature measurements per week&#8212;and one inner list per week.<\/p>\n<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=\"\"># Measurements of a temperature sensor (7 per week)\ntemperature = [[10, 8, 9, 12, 13, 7, 8], # week 1 [9, 9, 5, 6, 6, 9, 11], # week 2 [10, 8, 8, 5, 6, 3, 1]] # week 3<\/pre>\n<p>How to filter out the colder weeks with average temperature value &lt;8? This is the output you desire:<\/p>\n<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=\"\">print(cold_weeks)\n# [[9, 9, 5, 6, 6, 9, 11], [10, 8, 8, 5, 6, 3, 1]]<\/pre>\n<p>There are two semantically equivalent methods to achieve this: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">list comprehension<\/a> and the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-get-rid-of-pythons-map-function-with-list-comprehension\/\" target=\"_blank\"><code>map()<\/code> function<\/a>. Let&#8217;s explore both variants next.<\/p>\n<p>If you&#8217;re short on time, you can also get a quick overview by playing with the code in your web browser&#8212;I&#8217;ll explain the code after that.<\/p>\n<figure><iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/filterlistoflistshowto?lite=true\" allowfullscreen=\"true\" width=\"100%\" height=\"1000px\"><\/iframe><\/figure>\n<h2>Method 1: List Comprehension<\/h2>\n<p>The most Pythonic way of filtering a list\u2014in my opinion\u2014is the list comprehension statement <code>[x for x in list if condition]<\/code>. You can replace <code>condition<\/code> with any function of <code>x<\/code> you would like to use as a filtering condition. Only elements that are in the <code>list<\/code> <strong>and <\/strong>meet the <code>condition<\/code> are included in the newly created list.<\/p>\n<p><strong>Solution<\/strong>: Here&#8217;s how you can solve the above problem to filter a list of lists based on a function of the inner lists:<\/p>\n<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=\"\"># Measurements of a temperature sensor (7 per week)\ntemperature = [[10, 8, 9, 12, 13, 7, 8], # week 1 [9, 9, 5, 6, 6, 9, 11], # week 2 [10, 8, 8, 5, 6, 3, 1]] # week 3 # How to filter weeks with average temperature &lt;8? # Method 1: List Comprehension\ncold_weeks = [x for x in temperature if sum(x)\/len(x)&lt;8]\nprint(cold_weeks)\n# [[9, 9, 5, 6, 6, 9, 11], [10, 8, 8, 5, 6, 3, 1]]<\/pre>\n<p>The second and third list in the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-sum-list-of-lists-in-python-rows\/\" target=\"_blank\">list of lists<\/a> meet the condition of having an average temperature of less than 8 degrees. So those are included in the variable <code>cold_weeks<\/code>. <\/p>\n<p>You can visualize the memory usage of this code snippet in the following interactive tool:<\/p>\n<p> <iframe loading=\"lazy\" width=\"800\" height=\"500\" frameborder=\"0\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=%23%20Measurements%20of%20a%20temperature%20sensor%20%287%20per%20week%29%0Atemperature%20%3D%20%5B%5B10,%208,%209,%2012,%2013,%207,%208%5D,%20%23%20week%201%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B9,%209,%205,%206,%206,%209,%2011%5D,%20%23%20week%202%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B10,%208,%208,%205,%206,%203,%201%5D%5D%20%23%20week%203%0A%0A%0A%23%20How%20to%20filter%20weeks%20with%20average%20temperature%20%3C8%3F%0A%0A%23%20Method%201%3A%20List%20Comprehension%0Acold_weeks%20%3D%20%5Bx%20for%20x%20in%20temperature%20if%20sum%28x%29\/len%28x%29%3C8%5D%0Aprint%28cold_weeks%29&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=0&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<p>This is the most efficient way of filtering a list and it\u2019s also the most Pythonic one. If you look for alternatives though, keep reading.<\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension-python-list-of-lists\/\" target=\"_blank\">List Comprehension &#8212; Python List of Lists<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists-filter-vs-list-comprehension-which-is-faster\/\" target=\"_blank\">Filter() vs List Comprehension<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-does-nested-list-comprehension-work-in-python\/\" target=\"_blank\">Nested List Comprehension<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">The Ultimate Guide to Python Lists<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\">List Comprehension<\/a><\/li>\n<\/ul>\n<h2>Method 2: Filter() Function<\/h2>\n<p>The <code>filter(function, iterable)<\/code> function takes a function as input that takes on argument (a list element) and returns a Boolean value that indicates whether this list element should pass the filter. All elements that pass the filter are returned as a new <code>iterable<\/code> object (a filter object).<\/p>\n<p>You can use the <code>lambda<\/code> function statement to create the function right where you pass it as an argument. The syntax of the lambda function is <code>lambda x: expression<\/code> and it means that you use <code>x<\/code> as an input argument and you return expression as a result (that can or cannot use <code>x<\/code> to decide about the return value). For more information, see my <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" target=\"_blank\">detailed blog article about the lambda function<\/a>.<\/p>\n<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=\"\"># Measurements of a temperature sensor (7 per week)\ntemperature = [[10, 8, 9, 12, 13, 7, 8], # week 1 [9, 9, 5, 6, 6, 9, 11], # week 2 [10, 8, 8, 5, 6, 3, 1]] # week 3 # How to filter weeks with average temperature &lt;8? # Method 2: Map()\ncold_weeks = list(filter(lambda x: sum(x) \/ len(x) &lt; 8, temperature))\nprint(cold_weeks)\n# [[9, 9, 5, 6, 6, 9, 11], [10, 8, 8, 5, 6, 3, 1]]<\/pre>\n<p>Again, the second and third list in the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-sum-list-of-lists-in-python-rows\/\" target=\"_blank\">list of lists<\/a> meet the condition of having an average temperature of less than 8 degrees. So those are included in the variable <code>cold_weeks<\/code>.<\/p>\n<p>The <code>filter()<\/code> function returns a filter object that\u2019s an <code>iterable<\/code>. To convert it to a list, you use the <code>list(...)<\/code> constructor.<\/p>\n<p>Play with this code by clicking &#8220;Next&#8221; in the interactive code visualization tool:<\/p>\n<p> <iframe loading=\"lazy\" width=\"800\" height=\"500\" frameborder=\"0\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=%23%20Measurements%20of%20a%20temperature%20sensor%20%287%20per%20week%29%0Atemperature%20%3D%20%5B%5B10,%208,%209,%2012,%2013,%207,%208%5D,%20%23%20week%201%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B9,%209,%205,%206,%206,%209,%2011%5D,%20%23%20week%202%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B10,%208,%208,%205,%206,%203,%201%5D%5D%20%23%20week%203%0A%0A%0A%23%20How%20to%20filter%20weeks%20with%20average%20temperature%20%3C8%3F%0A%0A%23%20Method%202%3A%20Map%28%29%0Acold_weeks%20%3D%20list%28filter%28lambda%20x%3A%20sum%28x%29%20\/%20len%28x%29%20%3C%208,%20temperature%29%29%0Aprint%28cold_weeks%29&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=0&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-filter-in-python-using-lambda-functions\/\" target=\"_blank\">How to Filter Using the Lambda Function<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/which-is-faster-list-comprehension-or-map-function-in-python\/\" target=\"_blank\">Which is Faster &#8211; List Comprehension or Map()?<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-filter-in-python-using-lambda-functions\/\" target=\"_blank\">How to Filter Using the Lambda Function?<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Programming Tutorial<\/a><\/li>\n<\/ul>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x, and False otherwise. Lists belong to the most important data structures in Python&#8212;every [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-112686","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112686","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=112686"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112686\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=112686"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=112686"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=112686"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}