Lambda with filter() in Python - Time & Space Complexity
When using lambda functions with filter(), it's important to know how the program's running time changes as the input list grows.
We want to find out how many times the filter checks each item as the list gets bigger.
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered)
This code filters out even numbers from a list using a lambda function inside filter().
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The filter function applies the lambda check to each item in the list.
- How many times: Once for every item in the input list.
As the list gets bigger, the number of checks grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to filter grows evenly as the list gets longer.
[X] Wrong: "Using lambda with filter() makes the code run faster than a normal loop."
[OK] Correct: Lambda with filter() still checks every item once, so it takes about the same time as a loop.
Understanding how filter and lambda work together helps you explain how your code handles data efficiently in real projects.
"What if we changed the input from a list to a generator? How would the time complexity change?"