Built-in scope in Python - Time & Space Complexity
Let's explore how time complexity relates to using Python's built-in scope.
We want to see how the program's steps grow when it uses built-in functions repeatedly.
Analyze the time complexity of the following code snippet.
def sum_of_squares(numbers):
total = 0
for num in numbers:
total += abs(num) ** 2
return total
nums = [1, -2, 3, -4, 5]
print(sum_of_squares(nums))
This code calculates the sum of squares of absolute values from a list using built-in functions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the input list.
As the list gets longer, the program does more work, one step per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the basic steps |
| 100 | About 100 times the basic steps |
| 1000 | About 1000 times the basic steps |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[X] Wrong: "Using built-in functions makes the code run instantly, no matter the input size."
[OK] Correct: Built-in functions are fast but still run once per item, so time grows with input size.
Understanding how built-in functions affect time helps you explain your code clearly and shows you know how programs scale.
"What if we replaced the loop with a list comprehension using the same built-in functions? How would the time complexity change?"