filter()Intermediate Examples

Returns elements from an iterable for which a function returns True

filter() with keyword arguments

Using filter() with optional parameters and in iteration patterns.

python
# filter() with None
values = [0, 1, "", "hello", None, [], [1]]
print(list(filter(None, values)))

# Chaining filter and map
nums = range(20)
result = list(map(lambda x: x**2, filter(lambda x: x % 3 == 0, nums)))
print(result)

filter() supports additional parameters that modify its behavior.

filter() in real-world code

Practical patterns using filter().

python
# Common filter() patterns in production code
print("filter() is frequently used for data transformation")

# Example: processing a list
data = [1, 2, 3, 4, 5]
print(f"Sum: {sum(data)}")
print(f"Max: {max(data)}")
print(f"Sorted: {sorted(data, reverse=True)}")

These patterns show how filter() is commonly used in production code.

Want to try these examples interactively?

Open Intermediate Playground