enumerate() function in Python - Time & Space Complexity
We want to understand how long it takes to run code that uses the enumerate() function.
Specifically, we ask: how does the time grow when the list we use enumerate() on gets bigger?
Analyze the time complexity of the following code snippet.
items = ['apple', 'banana', 'cherry', 'date']
for index, value in enumerate(items):
print(f"{index}: {value}")
This code goes through each item in the list and prints its position and value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item in the list.
As the list gets bigger, the code runs longer because it visits each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times |
| 100 | About 100 times |
| 1000 | About 1000 times |
Pattern observation: The time grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Using enumerate() makes the code slower because it adds extra work."
[OK] Correct: enumerate() just keeps track of the position while looping, which is done in the same pass, so it does not add extra loops or slow down the code noticeably.
Understanding how simple loops like those with enumerate() scale helps you explain your code clearly and shows you know how to think about efficiency.
"What if we nested another loop inside that uses enumerate() on the same list? How would the time complexity change?"