0
0
Pythonprogramming~5 mins

sum() function in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: sum() function
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

When the list has more numbers, sum() has to add more times.

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

Pattern observation: The work grows directly with the number of items. Double the items, double the additions.

Final Time Complexity

Time Complexity: O(n)

This means the time to add numbers grows in a straight line with how many numbers there are.

Common Mistake

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

Interview Connect

Knowing how sum() works helps you understand how simple tasks can grow with input size, a key skill for writing efficient code.

Self-Check

"What if we used sum() on a list of lists instead of numbers? How would the time complexity change?"