Why list comprehension is used in Python - Performance Analysis
We want to see how using list comprehension affects the time it takes to create lists.
How does the time grow when we make bigger lists this way?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
This code creates a new list of squares from an existing list of numbers using list comprehension.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying each number by itself inside the list comprehension.
- How many times: Once for each item in the original list.
As the list gets bigger, the number of multiplications grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to create the new list grows in a straight line with the size of the input list.
[X] Wrong: "List comprehension is faster because it uses magic and skips loops."
[OK] Correct: List comprehension still does a loop under the hood; it just looks cleaner. The time depends on how many items you process.
Understanding how list comprehension scales helps you write clear and efficient code that interviewers appreciate.
"What if we used a nested list comprehension to create pairs? How would the time complexity change?"