Sobes.tech
Junior — Middle

Can you explain how the filter function works in Python and its features?

sobes.tech AI

Answer from AI

The filter function in Python is used to select elements from an iterable based on a given predicate function.

Syntax:

filter(function, iterable)
  • function — a function that takes an element and returns True or False.
  • iterable — a sequence from which elements are selected.

filter returns an iterator with elements for which the function returned True.

Example:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # Outputs: [2, 4, 6]

Features:

  • Returns an iterator, so to get a list, you need to explicitly convert it.
  • Allows concise filtering of data without writing loops.
  • If function is None, it filters elements that are True by default.