len() function in Python - Time & Space Complexity
Let's explore how the time it takes to find the length of a collection changes as the collection grows.
We want to know how the len() function's work changes with bigger inputs.
Analyze the time complexity of the following code snippet.
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)
This code finds and prints the number of items in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the stored length value of the list.
- How many times: Exactly once, no loops or repeated steps.
Finding the length does not need to count items one by one each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work stays the same no matter how big the list is.
Time Complexity: O(1)
This means finding the length takes the same quick step no matter the size of the list.
[X] Wrong: "len() counts every item each time, so it gets slower with bigger lists."
[OK] Correct: Python stores the length, so len() just reads that stored number instantly.
Knowing that len() is very fast helps you write clear and efficient code without worrying about hidden slow parts.
"What if we used a custom linked list without a stored length? How would len() behave then?"