define filter method
The filter() method in Python is used to select (filter) elements from an iterable (like a list,
tuple, etc.) based on a condition.
Definition:
filter() takes a function and an iterable, and returns only those elements for which the
function returns True.
Syntax:
filter(function, iterable)
function → condition to test each element
iterable → collection of elements (list, tuple, etc.)
Example 1: Filter Even Numbers
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4, 6]
Example 2: Filter Strings Starting with Vowel
words = ["apple", "banana", "orange", "grapes"]
vowels = list(filter(lambda x: x[0].lower() in 'aeiou', words))
print(vowels)
Output:
['apple', 'orange']