Filter Function
The built-in filter() function constructs an iterator from elements of an iterable for which a function returns True (or a truthy value). Syntax: filter(fu...
What is filter()?
The built-in filter() function constructs an iterator from elements of an iterable for which a function returns True (or a truthy value). Syntax: filter(function, iterable). Example: evens = list(filter(lambda x: x % 2 == 0, range(10))) gives [0, 2, 4, 6, 8]. Like map(), filter() returns a lazy iterator in Python 3. The original iterable is not modified; filter produces a new sequence containing only the elements that pass the test.
filter() with None
If you pass None as the function argument, filter() uses the truthiness of each element as the test: filter(None, [0, 1, "", "hello", [], [1,2], None, True]) returns an iterator yielding 1, "hello", [1,2], and True — the truthy elements. This is a concise way to remove all falsy values from a sequence. It is equivalent to [x for x in seq if x] but uses filter() idiomatically.
filter() vs List Comprehension
Like map(), filter() has a list comprehension equivalent. filter(lambda x: x > 0, nums) is equivalent to [x for x in nums if x > 0]. The list comprehension is generally preferred for readability. filter() is cleaner when the test function already exists as a named function: list(filter(str.isupper, ["Hello", "WORLD", "abc"])) selects only fully uppercase strings. When the test requires an inline lambda, list comprehensions are typically more Pythonic.
Combining filter() and map()
filter() and map() can be chained to build data pipelines. Get the squares of all even numbers in a list: result = list(map(lambda x: x**2, filter(lambda x: x%2==0, range(10)))) gives [0, 4, 16, 36, 64]. Reading inside-out: filter produces evens; map squares them. The same result with a list comprehension: [x**2 for x in range(10) if x%2==0]. Both are valid; the comprehension is often more readable for simple pipelines.
Filtering Dictionaries
filter() works on dictionary items when you iterate over items(): data = {"a": 1, "b": -2, "c": 3}; filtered = dict(filter(lambda item: item[1] > 0, data.items())) gives {"a": 1, "c": 3}. This pattern extracts a sub-dictionary meeting a condition. The equivalent dict comprehension is {k: v for k, v in data.items() if v > 0}. In practice the dict comprehension is preferred, but filter() with a named predicate function can improve clarity when the condition is complex.
Exam Tip
Exam questions test whether you know that filter() returns an iterator (not a list) in Python 3. Common question: what is the difference between map() and filter()? map() transforms every element; filter() selects a subset of elements. Also know that filter() with a function that always returns True gives you all elements; with a function that always returns False gives you an empty iterator. A common multiple-choice trap: list(filter(None, [0, False, None, "", 42])) — the answer is [42], not [0, False, None, "", 42].