__init__ method behavior in Python - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Creating a Person object by running
__init__once per loop. - How many times: Exactly
ntimes, once for each object created.
Each new object requires running __init__ once, so the total work grows directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 initializations |
| 100 | 100 initializations |
| 1000 | 1000 initializations |
Pattern observation: The work grows in a straight line as we add more objects.
Time Complexity: O(n)
This means the time to create all objects grows directly with how many objects we make.
[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.
Understanding how object creation time grows helps you explain how programs handle many items efficiently.
"What if the __init__ method included a loop that runs m times inside it? How would the time complexity change?"