Editor settings

General settings

Save settings

Learn to program with Python

Filter a List with Lambda Function #

Write a function filter_list(the_list, condition) that takes a list the_list and a lambda function condition as input. The function should filter the given list based on the given condition and return a new list containing only the elements that satisfy the condition.

For example:

the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
condition = lambda x: x % 2 == 0  # filter even numbers
filtered_list = filter_list(the_list, condition)
print(filtered_list)  # Output: [2, 4, 6, 8, 10]

Tests #

  • filter_list([-2, -1, 0, 1, 2, 3, 4, 5], lambda x: x >= 0) should return [0, 1, 2, 3, 4, 5]
  • filter_list([10.0, 15, 2, 2.5, 9, -1, 9.9], lambda x: type(x) == int) should return [15, 2, 9, -1]
  • filter_list([1, "b", 3, "d", 5, "f"], lambda x: type(x) == str) should return ["b", "d", "f"]
Output will be displayed here