0
0
Pythonprogramming~5 mins

abs() and round() in Python - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the list gets bigger, the number of times we call abs() and round() grows the same way.

Input Size (n)Approx. Operations
10About 20 calls (2 per number)
100About 200 calls
1000About 2000 calls

Pattern observation: The total work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets longer.

Common Mistake

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

Interview Connect

Understanding how simple built-in functions behave with input size helps you explain your code clearly and think about efficiency in real tasks.

Self-Check

What if we applied abs() and round() to a nested list of numbers instead of a flat list? How would the time complexity change?