How To Use Filter Function In Python

Pavol Kutaj
1 min readMay 7, 2022

The aim of this page📝is to document the general higher-order function filter() 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']
  • As a reminder there are 1+6 (False + falsy) values that — if tested — evaluate to False in Python

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com