0
0
Pythonprogramming~5 mins

Lambda with filter() in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda with filter()
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the number of checks grows directly with the number of items.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows in a straight line with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to filter grows evenly as the list gets longer.

Common Mistake

[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.

Interview Connect

Understanding how filter and lambda work together helps you explain how your code handles data efficiently in real projects.

Self-Check

"What if we changed the input from a list to a generator? How would the time complexity change?"