filter in Python

What is filter?

The filter() function constructs an iterator from elements of an iterable for which a function returns True. It is commonly used to select elements based on a condition.

Basic Syntax

filter(function, iterable)

Examples

# 1. Filtering even numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # Output: [2, 4, 6]
  
# 2. Filtering out empty strings
words = ["apple", "", "banana", None, "cherry", ""]
non_empty = filter(None, words)
print(list(non_empty))  # Output: ['apple', 'banana', 'cherry']
  
# 3. Using filter with a named function
def is_positive(n):
    return n > 0

numbers = [-2, 0, 3, 5, -1]
positive_numbers = filter(is_positive, numbers)
print(list(positive_numbers))  # Output: [3, 5]
  
# 4. Filtering characters from a string
chars = filter(lambda c: c.isalpha(), "a1b2c3")
print(''.join(chars))  # Output: abc
  
# 5. Filtering using None as function
values = [0, 1, False, True, '', 'Hello']
filtered = filter(None, values)
print(list(filtered))  # Output: [1, True, 'Hello']