String representation methods in Python - Time & Space Complexity
Let's explore how the time it takes to create string representations changes as the input grows.
We want to know how the work grows when we convert objects or data to strings.
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
n = 10 # Example value for n
people = [Person(f"Name{i}", i) for i in range(n)]
for p in people:
print(str(p))
This code creates a list of people and prints their string representations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of people and calling
str()on each. - How many times: Exactly
ntimes, once for each person.
As the number of people grows, the total work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 string conversions |
| 100 | 100 string conversions |
| 1000 | 1000 string conversions |
Pattern observation: Doubling the number of people doubles the work.
Time Complexity: O(n)
This means the time to create all string representations grows directly with the number of items.
[X] Wrong: "Calling str() on each object is constant time overall because each call is fast."
[OK] Correct: Even if one call is fast, doing it n times adds up, so total time grows with n.
Understanding how string conversions scale helps you explain performance when working with lists or collections in real projects.
"What if the __str__ method included a loop over a list inside each object? How would the time complexity change?"