abs() and round() in Python - Time & Space Complexity
We want to understand how the time it takes to run abs() and round() changes as the input size changes.
Specifically, how does the cost grow when we use these functions on numbers or lists?
Analyze the time complexity of using abs() and round() on a list of numbers.
numbers = [3.14, -2.71, 0, 7.5, -1.2]
results = []
for num in numbers:
a = abs(num)
r = round(num)
results.append((a, r))
This code takes each number, finds its absolute value and rounds it, then stores the results.
Look at what repeats as the input grows.
- Primary operation: Looping through each number in the list.
- How many times: Once for each number in the list (n times).
As the list gets bigger, the number of times we call abs() and round() grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 calls (2 per number) |
| 100 | About 200 calls |
| 1000 | About 2000 calls |
Pattern observation: The total 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 list gets longer.
[X] Wrong: "abs() and round() take longer on bigger numbers, so time grows with number size."
[OK] Correct: These functions run in constant time regardless of the number's value; time depends on how many numbers you process, not their size.
Understanding how simple built-in functions behave with input size helps you explain your code clearly and think about efficiency in real tasks.
What if we applied abs() and round() to a nested list of numbers instead of a flat list? How would the time complexity change?