Sobes.tech
Senior

How long does it take to add an element at the beginning and end of a list in Python?

sobes.tech AI

Answer from AI

In Python, the complexity of list insertion operations depends on the position:

  • Adding to the end of the list (list.append()) operates in amortized O(1) time, as lists are implemented as dynamic arrays.
  • Adding to the beginning of the list (list.insert(0, value)) operates in O(n), because all elements are shifted to the right to make space.

If you need to efficiently add elements to both the beginning and the end, it's better to use collections.deque, where both operations are performed in O(1):

from collections import deque

d = deque()
d.append(1)       # adding to the end — O(1)
d.appendleft(0)   # adding to the beginning — O(1)
How long does it take to add an element at the… - sobes.tech