Sobes.tech
Junior — Middle

How to determine the time complexity of retrieving the last element from a list in Python?

sobes.tech AI

Answer from AI

In Python, the time complexity of extracting the last element from a list depends on the data structure type:

  • For a standard list (list), accessing an element by index is an O(1) operation, as lists are implemented as arrays.

Example:

lst = [1, 2, 3, 4, 5]
last_element = lst[-1]  # O(1)
  • For other structures, such as linked lists, access to the last element can be O(n), as it requires traversing all elements.

In standard Python list, extracting the last element is a constant-time operation.