List comprehension vs loop in Python - Performance Comparison
We want to see how the time it takes to create a list changes when using list comprehension versus a loop.
How does the method affect the speed as the list size grows?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
squares_loop = []
for n in numbers:
squares_loop.append(n * n)
squares_comp = [n * n for n in numbers]
This code creates a list of squares of numbers using a loop and a list comprehension.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying each number by itself and adding it to a list.
- How many times: Once for each number in the input list.
Each number is processed one time, so the work grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications and 10 append operations |
| 100 | 100 multiplications and 100 append operations |
| 1000 | 1000 multiplications and 1000 append operations |
Pattern observation: The number of operations grows evenly as the list gets bigger.
Time Complexity: O(n)
This means the time to create the new list grows in a straight line with the number of items.
[X] Wrong: "List comprehension is always faster because it has better time complexity."
[OK] Correct: Both methods do the same number of steps, so their time complexity is the same; speed differences come from how Python runs them internally, not from complexity.
Understanding how loops and list comprehensions scale helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we used nested loops or nested list comprehensions? How would the time complexity change?"