How To Use Filter Function In Python

1. DEFINITION

  • filter() passes each element of an input collection into a specific, filtering function
  • it returns a new iterable object of type of the filtering function
  • it returns only those elements of the input collection which the filtering function returns True

2. EXAMPLE

""" FILTER WITH LAMBDA FILTERING FUNCTION """
>>> positives = filter(lambda x: x > 0, [1, -5, 0, 6])
""" RETURNS LAZY ITERABLE """
>>> positives
<filter object at 0x0250F628>
""" FORCE EVALUATION WITH A LIST CONSTRUCTOR """
>>> list(positives)
[1, 6]

3. LIKE AND UNLIKE MAP FUNCTION

  1. like map(), filter is a general higher order function that accepts/applies a specific function to each element in a sequence
  2. like map(), it produces its results lazily (as opposed to Python 2)
  3. unlike map(), filter() only accepts a single input sequence and the function must accept only a single argument

4. NONE AS THE FIRST ARGUMENT

  • instead of a specific filtering function, also None can be passed as the first argument to filter()
  • this will filter out input elements that evaluate to False in boolean context
  • this means that you can easily remove all False and falsy values from an input collection
>>> trues = filter(None,[0,1,False,True,[],[1,2,3],"","hello"])
>>> list(trues)
[1, True, [1, 2, 3], 'hello']

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com