Middle
What is the complexity of inserting an element into a list in Python?
sobes.tech AI
Answer from AI
The complexity of inserting into a list in Python depends on the position of insertion.
- Insert at the end (
append()): O(1) on average, O(n) in the worst case (when resizing the array). - Insert at the beginning (
insert(0, element)): O(n), since all existing elements need to be shifted. - Insert in the middle (
insert(index, element)): O(n), since elements from the insertion point to the end need to be shifted.
# Examples
my_list = [1, 2, 3]
# Insert at the end - O(1) on average
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
# Insert at the beginning - O(N)
my_list.insert(0, 0)
print(my_list) # Output: [0, 1, 2, 3, 4]
# Insert in the middle - O(N)
my_list.insert(2, 99)
print(my_list) # Output: [0, 1, 99, 2, 3, 4]