Junior — Middle
Can you explain what the filter function in Python is and how it is used for data processing?
sobes.tech AI
Answer from AI
The filter function in Python is used to filter elements of an iterable object (such as a list) based on a given condition. It takes two arguments: a function that returns True or False for each element, and the iterable object itself.
As a result, filter returns an iterator containing only those elements for which the function returned True.
Example of usage:
numbers = [1, 2, 3, 4, 5, 6]
# Keep only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Outputs: [2, 4, 6]
Thus, filter helps to conveniently and efficiently process data by selecting the desired elements based on a specified criterion.