sum() function in Python - Time & Space Complexity
We want to understand how the time it takes to add numbers grows as we add more numbers together using the sum() function.
How does the work change when the list of numbers gets bigger?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
This code adds all the numbers in a list and prints the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number in the list one by one.
- How many times: Once for each number in the list.
When the list has more numbers, sum() has to add more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the additions.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line with how many numbers there are.
[X] Wrong: "sum() adds all numbers instantly, no matter how many there are."
[OK] Correct: sum() must look at each number to add it, so more numbers mean more work.
Knowing how sum() works helps you understand how simple tasks can grow with input size, a key skill for writing efficient code.
"What if we used sum() on a list of lists instead of numbers? How would the time complexity change?"