0
0
Pythonprogramming~5 mins

Polymorphism through functions in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Polymorphism through functions
O(n)
Understanding Time Complexity

Let's explore how the time needed to run a function changes when it can work with different types of inputs.

We want to see how the function's work grows as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


def process(items):
    result = []
    for item in items:
        result.append(str(item))
    return result

values = [1, 2, 3, 4, 5]
print(process(values))

This function takes a list of items and converts each item to a string, collecting the results.

Identify Repeating Operations
  • Primary operation: Looping through each item in the input list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the function does more work by converting more items.

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

Pattern observation: The 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 with the input size.

Common Mistake

[X] Wrong: "Polymorphism makes the function slower because it handles different types."

[OK] Correct: The function still processes each item once; the type difference does not add extra loops or steps.

Interview Connect

Understanding how functions handle different inputs without extra cost shows you know how to write flexible and efficient code.

Self-Check

"What if the function called another function inside the loop that itself loops over the item? How would the time complexity change?"