0
0
Pythonprogramming~5 mins

len() function in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: len() function
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Finding the length does not need to count items one by one each time.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The work stays the same no matter how big the list is.

Final Time Complexity

Time Complexity: O(1)

This means finding the length takes the same quick step no matter the size of the list.

Common Mistake

[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.

Interview Connect

Knowing that len() is very fast helps you write clear and efficient code without worrying about hidden slow parts.

Self-Check

"What if we used a custom linked list without a stored length? How would len() behave then?"