Iterating over lists in Python - Time & Space Complexity
When we go through each item in a list one by one, it takes some time. We want to understand how this time changes when the list gets bigger.
The question is: How does the time to look at every item grow as the list grows?
Analyze the time complexity of the following code snippet.
def print_items(items):
for item in items:
print(item)
my_list = [1, 2, 3, 4, 5]
print_items(my_list)
This code goes through each item in a list and prints it out.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the number of times we print grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The number of steps grows directly with the size of the list.
Time Complexity: O(n)
This means if the list doubles in size, the time to go through it also doubles.
[X] Wrong: "Looping through a list always takes the same time no matter how big the list is."
[OK] Correct: The time depends on how many items are in the list. More items mean more steps.
Understanding how looping through lists grows with size helps you explain your code clearly and shows you know how programs handle data efficiently.
"What if we nested one loop inside another to go through the list twice? How would the time complexity change?"