List creation and representation in Python - Time & Space Complexity
When we create and show lists in Python, it is important to understand how the time needed grows as the list gets bigger.
We want to know how the work changes when the list size changes.
Analyze the time complexity of the following code snippet.
my_list = []
for i in range(n):
my_list.append(i)
print(my_list)
This code creates a list by adding numbers from 0 up to n-1, then prints the whole list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an item to the list inside the loop.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of times we add items grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the size of the list. Double the size, double the work.
Time Complexity: O(n)
This means the time to create and print the list grows in a straight line with the number of items.
[X] Wrong: "Adding items to a list inside a loop is instant and does not depend on list size."
[OK] Correct: Each addition happens once per item, so more items mean more additions and more time.
Understanding how list creation time grows helps you explain and predict performance in real coding tasks.
"What if we used list comprehension instead of a loop with append? How would the time complexity change?"