What is the time complexity of inserting and deleting elements in a list?

Time Complexity of Insertion and Deletion in a Python List

Python lists are implemented as dynamic arrays, which affects the time complexity of insertion and deletion operations.


1. Inserting Elements into a List
a) append() – Add at the End
my_list.append(10)  # Adds element at the end
  • Time Complexity: O(1) (Amortized)
  • Why? Appending at the end is usually constant time, but occasional resizing may cause O(n) when the array expands.
b) insert(index, value) – Insert at a Specific Position
my_list.insert(2, 50)  # Inserts 50 at index 2
  • Time Complexity: O(n)
  • Why? Inserting in the middle shifts all elements after the index.

2. Deleting Elements from a List
a) pop() – Remove from the End
my_list.pop()  # Removes the last element
  • Time Complexity: O(1)
  • Why? Removing from the end does not require shifting elements.
b) pop(index) – Remove from a Specific Position
my_list.pop(2)  # Removes element at index 2
  • Time Complexity: O(n)
  • Why? Removing an element from the middle requires shifting elements to fill the gap.
c) remove(value) – Remove by Value
my_list.remove(50)  # Removes first occurrence of 50
  • Time Complexity: O(n)
  • Why? It first searches for the value (O(n)) and then removes it (O(n), worst case).

Summary Table
Operation Method Time Complexity
Insert at End append() O(1) (Amortized)
Insert at Middle insert(i, x) O(n)
Delete at End pop() O(1)
Delete at Middle pop(i) O(n)
Delete by Value remove(x) O(n)