Editor

Custom Filter

Functions · Intermediate · 65 XP · about 6 min

Write a function called custom_filter(lst, func) that returns a new list containing only the elements for which the function returns True.

This is similar to Python's built-in filter() function!

Example

custom_filter([1, 2, 3, 4, 5], lambda x: x > 2)  # Returns [3, 4, 5]
custom_filter([1, 2, 3, 4], lambda x: x % 2 == 0)  # Returns [2, 4]
custom_filter(["a", "bb", "ccc"], lambda x: len(x) > 1)  # Returns ["bb", "ccc"]

Requirements

  • Return a new list (don't modify the original)
  • The function func takes one argument and returns True/False
  • Handle empty lists
def custom_filter(lst, func):
# Your code here
pass
# Test your function
print(custom_filter([1, 2, 3, 4, 5], lambda x: x > 2))
print(custom_filter([1, 2, 3, 4], lambda x: x % 2 == 0))

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.