0
0
Pythonprogramming~5 mins

List indexing and slicing in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: List indexing and slicing
O(1) for indexing, O(k) for slicing
Understanding Time Complexity

When working with lists, it is important to know how fast we can access or extract parts of the list.

We want to understand how the time to get an item or a slice changes as the list grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

my_list = list(range(1000))
item = my_list[500]       # indexing
sub_list = my_list[100:200]  # slicing

This code gets one item by index and then gets a slice (a part) of the list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing one item by index and copying a slice of the list.
  • How many times: Indexing accesses one element directly; slicing copies each element in the slice range.
How Execution Grows With Input

Getting one item by index takes the same time no matter how big the list is.

Getting a slice takes time proportional to how many items are in the slice.

Input Size (n)Indexing OperationsSlicing Operations (length k)
101k (e.g., 5)
1001k (e.g., 20)
10001k (e.g., 100)

Pattern observation: Indexing time stays the same; slicing time grows with the slice size, not the whole list.

Final Time Complexity

Time Complexity: O(1) for indexing, O(k) for slicing

This means getting one item is very fast and does not depend on list size, but slicing depends on how many items you take.

Common Mistake

[X] Wrong: "Slicing a list is always as fast as indexing one item."

[OK] Correct: Slicing creates a new list by copying each item in the slice, so it takes longer if the slice is bigger.

Interview Connect

Understanding the difference between indexing and slicing helps you write efficient code and answer questions about list operations clearly.

Self-Check

"What if we slice the entire list instead of a small part? How would the time complexity change?"