Sobes.tech
Junior — Middle

What is the time complexity of retrieving an element by index in a list?

sobes.tech AI

Answer from AI

In Python, the time complexity of retrieving an element by index depends on the data structure type:

  • List: index access — an operation with a time complexity of O(1), as lists are implemented as dynamic arrays.

  • Linked list (e.g., collections.deque): index access — O(n), since it requires traversing the elements in order.

Example for a list:

my_list = [10, 20, 30, 40]
element = my_list[2]  # Fast access, O(1)
print(element)  # Will output 30

Thus, for a standard Python list, index retrieval is a very efficient operation.