filter() tests each element with the given function, keeping only the ones where the result is truthy, and produces a lazy iterator rather than an immediate list, the same lazy evaluation model as map(). Passing None as the function is a shorthand for keeping only the elements that are themselves truthy.
1Understanding filter()
filter() tests each element with the given function, keeping only the ones where the result is truthy, and produces a lazy iterator rather than an immediate list, the same lazy evaluation model as map(). Passing None as the function is a shorthand for keeping only the elements that are themselves truthy.
Passing None as the function to filter() is a quick way to drop falsy values, like empty strings, zero, None, and empty lists, out of an iterable.
numbers = [1, -2, 3, -4, 5]
positives = filter(lambda x: x > 0, numbers)
print(list(positives))2Practical Example
Here is a real-world application of filter() showing how it is used in production Python code.
names = ["Alice", "", "Bob", None, "Carol"]
valid_names = list(filter(None, names))
print(valid_names)3Best Practices
Follow these guidelines when working with filter():
1. Prefer a list comprehension with an if clause over filter() plus lambda for simple conditions, since it reads more naturally
2. Use filter() with None as the function to strip out falsy values in one step
3. Wrap filter() in list() when you need the result more than once, since it's a single-pass iterator
Tip: Passing None as the function to filter() is a quick way to drop falsy values, like empty strings, zero, None, and empty lists, out of an iterable.
numbers = [1, -2, 3, -4, 5]
positives = filter(lambda x: x > 0, numbers)
print(list(positives))