Object initialization flow in Python - Time & Space Complexity
When we create objects in Python, some steps happen behind the scenes. Understanding how long these steps take helps us write faster programs.
We want to know how the time to set up an object changes as we add more data or features.
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name, hobbies):
self.name = name
self.hobbies = []
for hobby in hobbies:
self.hobbies.append(hobby)
p = Person("Alice", ["reading", "swimming", "coding"])
This code creates a Person object and copies a list of hobbies into a new list inside the object.
- Primary operation: The for-loop that goes through each hobby in the input list.
- How many times: Once for each hobby in the hobbies list.
As the number of hobbies grows, the time to copy them grows too, because each hobby is added one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to copy hobbies |
| 100 | About 100 steps to copy hobbies |
| 1000 | About 1000 steps to copy hobbies |
Pattern observation: The time grows directly with the number of hobbies. Double the hobbies, double the time.
Time Complexity: O(n)
This means the time to set up the object grows in a straight line with the number of hobbies you give it.
[X] Wrong: "Initializing an object always takes the same time, no matter how much data it has."
[OK] Correct: If the object copies or processes a list or other data, it takes longer when there is more data to handle.
Understanding how object setup time grows helps you explain your code choices clearly and shows you know how programs handle data behind the scenes.
"What if we changed the hobbies list to a set instead of a list? How would the time complexity change?"