{"id":1867,"date":"2019-12-29T11:51:43","date_gmt":"2019-12-29T11:51:43","guid":{"rendered":"https:\/\/www.askpython.com\/?p=1867"},"modified":"2022-08-06T13:09:14","modified_gmt":"2022-08-06T13:09:14","slug":"python-filter-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/built-in-methods\/python-filter-function","title":{"rendered":"Python filter() function"},"content":{"rendered":"\n<p>Python&#8217;s <code><strong>filter<\/strong>()<\/code> function is used to filter the elements of an iterable (sequence) with the help of a predicate that tests each element on the iterable.<\/p>\n\n\n\n<p>A predicate is a function that always returns <code><strong>True<\/strong><\/code> or <code><strong>False<\/strong><\/code>. We cannot use a generic function with <code>filter()<\/code>, since it returns all elements only if a suitable condition is met. This means that the filtering function must always return a boolean value, and thus, the filter function is a predicate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Format of filter()<\/h2>\n\n\n\n<p>Since this is a function that operates on a Python iterable, the iterable is one of the parameters. And since it tests a predicate on each element, the function is also another parameter which is required.<\/p>\n\n\n\n<p>And since it filters out elements from the sequence, it must also return an iterable, which only consists of the elements which satisfy the filtering function.<\/p>\n\n\n\n<p>But in this case, since we work with objects, Python returns us a <strong><em>filter object<\/em><\/strong> as an iterable, which will prove to be handy for conversion to other types, using methods like <code>list()<\/code> and <code>dict()<\/code>.<\/p>\n\n\n\n<p>Simple, isn&#8217;t it? Let us look at how we apply this and create working programs using <code>filter()<\/code>.<\/p>\n\n\n\n<p>Format: <code>filter_object = filter(predicate, iterable)<\/code><\/p>\n\n\n\n<p>Here is a very simple example that filters a list with a function that tests whether a number is odd or even.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\na = &#x5B;1, 2, 3, 4, 5]\n\n# We filter using a lambda function predicate.\n# This predicate returns true\n# only if the number is even.\nfilter_obj_even = filter(lambda x: x%2 == 0, a)\n\nprint(type(filter_obj_even))\n\n# Convert to a list using list()\nprint(&#039;Even numbers:&#039;, list(filter_obj_even))\n\n# We can also use define the predicate using def()\ndef odd(num):\n    return (num % 2) != 0\n\nfilter_obj_odd = filter(odd, a)\nprint(&#039;Odd numbers:&#039;, list(filter_obj_odd))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n&lt;class &#039;filter&#039;&gt;\nEven numbers: &#x5B;2, 4]\nOdd numbers: &#x5B;1, 3, 5]\n<\/pre><\/div>\n\n\n<p>Note that we can get the individual elements of the filter object by iterating through it, since it is an iterable:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfor item in filter_obj_odd:\n    print(item)\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n1\n3\n5\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">filter() and None<\/h2>\n\n\n\n<p>We can also use <code>None<\/code> as a predicate with <code>filter()<\/code>. <code>None<\/code> returns <code>True<\/code> if the object has a boolean value of <code>True<\/code>, and <code>False<\/code> otherwise.<\/p>\n\n\n\n<p>This means that objects like <code>0<\/code>, <code>None<\/code>, <code>''<\/code>, <code>[]<\/code> etc, are all filtered out by <code>None<\/code> predicate, since they are empty element objects.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\na = &#x5B;0, 1, &#039;Hello&#039;, &#039;&#039;, &#x5B;], &#x5B;1,2,3], 0.1, 0.0]\n\nprint(list(filter(None, a)))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;1, &#039;Hello&#039;, &#x5B;1, 2, 3], 0.1]\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>We learned about the <code>filter()<\/code> function that Python provides us with, for applying a predicate on an iterable.<\/p>\n\n\n\n<p>The conciseness and readability of <code>filter<\/code> makes it a very popular function amongst Developers for modern Python codebases.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Python filter<\/li><li><a href=\"https:\/\/docs.python.org\/3.8\/library\/functions.html#filter\" target=\"_blank\" aria-label=\"Python.org API Doc (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"rank-math-link\">Python.org API Doc<\/a><\/li><\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s filter() function is used to filter the elements of an iterable (sequence) with the help of a predicate that tests each element on the iterable. A predicate is a function that always returns True or False. We cannot use a generic function with filter(), since it returns all elements only if a suitable condition [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-1867","post","type-post","status-publish","format-standard","hentry","category-built-in-methods"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1867","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=1867"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1867\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=1867"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=1867"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=1867"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}