0
0
Pythonprogramming~5 mins

Duck typing concept in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Duck typing concept
O(n)
Understanding Time Complexity

When using duck typing, we want to know how the program's speed changes as we work with different objects.

We ask: How does the program handle operations on objects that behave similarly but may be different types?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


def process_items(items):
    for item in items:
        item.quack()

class Duck:
    def quack(self):
        print("Quack!")

class Person:
    def quack(self):
        print("I'm pretending to be a duck!")

process_items([Duck(), Person(), Duck()])

This code calls the quack method on each object in a list, relying on duck typing to allow different types to respond similarly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item and calling quack().
  • How many times: Once for each item in the list.
How Execution Grows With Input

Each item in the list causes one call to quack(). So, the work grows directly with the number of items.

Input Size (n)Approx. Operations
1010 calls to quack()
100100 calls to quack()
10001000 calls to quack()

Pattern observation: The number of operations grows evenly as the list gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the number of items you process.

Common Mistake

[X] Wrong: "Duck typing makes the program slower because it checks types at runtime for every call."

[OK] Correct: The program just calls the method on each object without extra type checks; it trusts the object can respond, so the speed depends mainly on how many items you have.

Interview Connect

Understanding how duck typing affects time helps you explain how flexible code runs as data grows, showing you grasp both design and performance.

Self-Check

"What if each quack() method took longer because it did more work? How would that affect the overall time complexity?"