w3resource

What does the Python filter function do, and how is it used?

Python filter() Function: Filtering Elements with Examples

Python filter() function filters elements from an iterable (e.g., list, tuple) based on a specified condition (predicate). It returns an iterator containing only elements that satisfy the condition defined by the given function.

Syntax:

filter(function, iterable)

Arguments:

  • function: The function that tests each element of the iterable. Returns True or False based on whether the element should be included.
  • iterable: The collection of items from which the function filters the elements.

A filter() function applies the 'function' to each element in an iterable, returning an iterator containing only those elements that returned True for the filter.

Example:

# Define a function to check if a number is odd
def is_odd(x):
    return x % 2 != 0
# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter() to get only the odd numbers from the list
odd_numbers = filter(is_odd, numbers)
# Convert the iterator to a list to see the results
result = list(odd_numbers)
print(result)

Output:

[1, 3, 5, 7, 9]

For simple filtering operations, you can use a lambda function with filter():

# Create a list of numbers
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter() with a lambda function to get only the odd numbers
odd_nums = filter(lambda x: x % 2 != 0, nums)
# Convert the iterator to a list to see the results
result = list(odd_nums)
print(result)

Output:

[1, 3, 5, 7, 9]

The filter() function is a powerful tool for data filtering. It is commonly used in functional programming paradigms to extract specific elements from a collection based on a given condition.



Follow us on Facebook and Twitter for latest update.