with filter()
Introduction:
- In Python, you can use a lambda function in a
filter()function to filter elements based on a condition defined in the lambda function. Thefilter()function returns an iterator that passes elements through the lambda function and includes only those for which the condition is true.
Example:
Consider the following lambda function with
filter():pythonfilter(lambda x: x % 2 == 0, my_list)- This lambda function filters out only the even numbers from the list
my_list.
- This lambda function filters out only the even numbers from the list
Observation:
- The lambda function used in the
filter()must return a boolean value, indicating whether each element should be included in the resulting list.
Examples:
- Filter Even Numbers in a List Using a Lambda Function:
- This example defines a lambda function in the
filter()to filter out only even numbers from the listmy_list. Python Program:
pythonmy_list = [1, 2, 7, 4, 6, 9, 12, 16, 3] # Lambda function with filter() result = filter(lambda x: x % 2 == 0, my_list) # Converting the returned iterable to a list result = list(result) print(result)Output:
[2, 4, 6, 12, 16]
- This example defines a lambda function in the
- Filter Non-Empty Strings Using Lambda Function with filter():
- This example defines a lambda function with
filter()that filters out only non-empty strings from the given list of stringsmy_list. Python Program:
pythonmy_list = ['apple', '', '', 'banana', 'cherry', ''] # Lambda function with filter() result = filter(lambda x: len(x) != 0, my_list) # Converting the returned iterable to a list result = list(result) print(result)Output:
['apple', 'banana', 'cherry']
- This example defines a lambda function with
Exercises:
- Filter Odd Numbers:
Define a lambda function in the
filter()to filter out only odd numbers from a given list.pythonmy_list = [1, 2, 7, 4, 6, 9, 12, 16, 3] result = filter(lambda x: x % 2 != 0, my_list) result = list(result) print(result) # Output: [1, 7, 9, 3]
- Filter Positive Numbers:
Define a lambda function in the
filter()to filter out only positive numbers from a given list.pythonmy_list = [-1, 2, -7, 4, -6, 9, -12, 16, 3] result = filter(lambda x: x > 0, my_list) result = list(result) print(result) # Output: [2, 4, 9, 16, 3]
- Filter Strings Longer Than 3 Characters:
Define a lambda function in the
filter()to filter out only strings longer than 3 characters from a given list of strings.pythonmy_list = ['apple', 'cat', 'banana', 'dog', 'cherry'] result = filter(lambda x: len(x) > 3, my_list) result = list(result) print(result) # Output: ['apple', 'banana', 'cherry']
Summary:
- In this tutorial, we learned how to use a lambda function with
filter()to filter elements based on a condition. Thefilter()function is useful for creating concise and readable code when working with collections. Practice using lambda functions withfilter()to get comfortable with these powerful tools in your Python programs!