0
0
Pythonprogramming~5 mins

__init__ method behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: __init__ method behavior
O(n)
Understanding Time Complexity

Let's explore how the time it takes to run the __init__ method changes as we create more objects.

We want to know how the work grows when making many instances of a class.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = []
n = 10
for i in range(n):
    people.append(Person(f"Person{i}", i))

This code creates n Person objects, each with a name and age, and stores them in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a Person object by running __init__ once per loop.
  • How many times: Exactly n times, once for each object created.
How Execution Grows With Input

Each new object requires running __init__ once, so the total work grows directly with the number of objects.

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

Pattern observation: The work grows in a straight line as we add more objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows directly with how many objects we make.

Common Mistake

[X] Wrong: "The __init__ method runs only once no matter how many objects are created."

[OK] Correct: Each object needs its own setup, so __init__ runs every time we make a new object.

Interview Connect

Understanding how object creation time grows helps you explain how programs handle many items efficiently.

Self-Check

"What if the __init__ method included a loop that runs m times inside it? How would the time complexity change?"