Filtering Lists with Custom Criteria
Filtering lists is a fundamental operation in programming, allowing you to extract specific elements based on certain conditions. This challenge asks you to implement a function that filters a list of numbers based on a provided criteria, demonstrating your understanding of list comprehensions or the filter() function in Python. This skill is crucial for data processing, analysis, and many other applications.
Problem Description
You are tasked with creating a function called filter_list that takes two arguments: a list of integers (data) and a function (criteria). The criteria function should accept a single integer as input and return a boolean value (True or False). The filter_list function should return a new list containing only the elements from data for which the criteria function returns True. The original data list should remain unchanged.
Key Requirements:
- The function must accept a list of integers and a function as input.
- The function must apply the
criteriafunction to each element in thedatalist. - The function must return a new list containing only the elements that satisfy the
criteria. - The original
datalist must not be modified.
Expected Behavior:
The function should iterate through the input list, apply the provided criteria function to each element, and include the element in the output list only if the criteria function returns True.
Edge Cases to Consider:
- Empty input list: Should return an empty list.
criteriafunction always returnsFalse: Should return an empty list.criteriafunction always returnsTrue: Should return a copy of the original list.- Input list containing non-integer values (though the problem specifies integers, consider how your solution might handle this gracefully - raising an error or ignoring the element).
Examples
Example 1:
Input: data = [1, 2, 3, 4, 5, 6], criteria = lambda x: x % 2 == 0
Output: [2, 4, 6]
Explanation: The criteria function checks if a number is even. The output list contains only the even numbers from the input list.
Example 2:
Input: data = [10, 20, 30, 40, 50], criteria = lambda x: x > 30
Output: [40, 50]
Explanation: The criteria function checks if a number is greater than 30. The output list contains only the numbers greater than 30.
Example 3:
Input: data = [], criteria = lambda x: x > 5
Output: []
Explanation: The input list is empty, so the output list is also empty.
Constraints
datawill be a list of integers.criteriawill be a function that takes an integer and returns a boolean.- The length of
datacan be up to 1000. - The function should execute in O(n) time complexity, where n is the length of the input list.
Notes
Consider using a list comprehension or the built-in filter() function for a concise and efficient solution. Think about how to handle potential errors if the input list contains non-integer values, although the problem statement specifies integers. Focus on creating a readable and maintainable solution.