Kodewick
Start learning →
Inserting and deleting in a list7 / 52

Inserting and deleting in a list

Lesson 7 of 52 · Part 2 · Names, lists and linked lists · about 18 minutes

Inserting or deleting in a list moves every reference after that spot, so a.insert(0, x) and a.pop(0) are O(n), while append at the end moves nothing.

In a list of 100,000 numbers, a.insert(0, x) has to move every one of the 100,000 references back one slot to free slot 0. Insert at the front 100,000 times in a loop and that is about 5 billion moves; 100,000 appends move nothing at all. The last lesson showed that a list is a row of references side by side, which is why a[i] is fast. This lesson is the other side of it: the slots must stay side by side, so inserting or deleting in the middle moves everything after it.

Inserting in the middle: everything after moves back

Write it by hand first. Use a list of capacity 5 as a row of slots, with size saying how many are in use. To insert x at index pos: starting from the last one, move each item back one slot, then put x in the slot freed at pos.

data (size = 4, capacity 5)3791101234↑i
1for i in range(size, pos, -1):2    data[i] = data[i - 1]3    moves += 14data[pos] = x5size += 1

Inserting 5 at index 1: move items back starting from the last, then put 5 in the freed data[1]

Why back to front? Going front to back, data[2] = data[1] would overwrite the 9 first, and every later move would copy 7.

main.py
1def insert_at(data, size, pos, x):2    moves = 03    for i in range(size, pos, -1):4        data[i] = data[i - 1]5        moves += 16    data[pos] = x7    return size + 1, moves8 9data = [3, 7, 9, 11, None]10size, moves = insert_at(data, 4, 1, 5)11print(data[:size], "moved", moves)12 13print("insert at the front:", insert_at([3, 7, 9, 11, None], 4, 0, 1)[1])14print("insert at the end:", insert_at([3, 7, 9, 11, None], 4, 4, 13)[1])
Output
[3, 5, 7, 9, 11] moved 3
insert at the front: 4
insert at the end: 0

That is exactly what a.insert(pos, x) does in CPython (in C, moving a whole block at once, which is quick, but the number of items moved is the same). At the front it moves n items; at the end, none.

Guess the outputA wrong guess is fine

What does it print if the moves go front to back?

1data = [3, 7, 9, 11, None]2size, pos = 4, 13for i in range(pos, size):4    data[i + 1] = data[i]5data[pos] = 56print(data)
Choose one

The table holds [2, 4, 6, 8, 10] (size = 5, with room to spare). What does it look like after inserting 5 at index 2, and how many elements moved?

Change it

Change only pos in the green box so that 5 goes between 9 and 11 and it prints [3, 7, 9, 5, 11].

1data = [3, 7, 9, 11, None]2size, pos, x = 4, , 53for i in range(size, pos, -1):4    data[i] = data[i - 1]5data[pos] = x6print(data)
Should print
[3, 7, 9, 5, 11]

Deleting: everything after moves forward

To delete the item at index pos: the items after it move forward one slot each, front to back, covering it; then the last slot is cleared.

data (size = 5)35791101234↑i
1for i in range(pos, size - 1):2    data[i] = data[i + 1]3    moves += 14data[size - 1] = None5size -= 1

Deleting the 5 at index 1: the items after it move forward one by one, the last slot is cleared, size goes down by 1
main.py
1def delete_at(data, size, pos):2    moves = 03    for i in range(pos, size - 1):4        data[i] = data[i + 1]5        moves += 16    data[size - 1] = None7    return size - 1, moves8 9data = [3, 5, 7, 9, 11]10size, moves = delete_at(data, 5, 1)11print(data[:size], "moved", moves)12 13n = 100014print("pop(0):", delete_at(list(range(n)), n, 0)[1])15print("pop(): ", delete_at(list(range(n)), n, n - 1)[1])
Output
[3, 7, 9, 11] moved 3
pop(0): 999
pop():  0

The last slot is set to None so it no longer refers to that object: once nothing else refers to it, it can be reclaimed (lesson 5 has the details).

Guess the outputA wrong guess is fine

What does it print if a delete moves things back to front?

1data = [3, 5, 7, 9, 11]2size, pos = 5, 13for i in range(size - 2, pos - 1, -1):4    data[i] = data[i + 1]5print(data[:size - 1])
Choose one

A table with size = 5 (and room to spare). Which positions pos can you insert at? Which can you delete?

Exercise 1

Delete and count

Finish delete_at(data, size, pos): delete data[pos], move the items after it forward, set the last slot to None, and return the new size and how many items moved.

It should print
[3, 7, 9, 11] 3
[3, 7, 9] 0
[7, 9] 2
exercise1.py
1def delete_at(data, size, pos):2    moves = 03    # from pos to size - 2, copy the next item over; moves += 1 for each4    return size, moves5 6data = [3, 5, 7, 9, 11]7size, moves = delete_at(data, 5, 1)8print(data[:size], moves)9size, moves = delete_at(data, size, size - 1)10print(data[:size], moves)11size, moves = delete_at(data, size, 0)12print(data[:size], moves)
Output
Press Run or Ctrl+Enter

How many move depends on where

The number of moves depends only on the position: the further from the end, the more items move.

Operation (length n)Items movedCost
a.append(x)0O(1) (amortised, next lesson)
a.pop()0O(1)
a.insert(i, x)n − iO(n − i)
a.insert(0, x)nO(n)
a.pop(i), del a[i]n − 1 − iO(n − i)
a.pop(0)n − 1O(n)
a.remove(x)find it from the front, then move the rest: about n in allO(n)

One O(n) is nothing; O(n) every time round a loop is O(n²). Build a list of 400 numbers by inserting at the front, and compare with appending and then reversing:

main.py
1def build_front(n):2    data = [None] * n3    size = 04    moves = 05    for x in range(n):6        for i in range(size, 0, -1):   # each insert at the front: everything moves back7            data[i] = data[i - 1]8            moves += 19        data[0] = x10        size += 111    return data, moves12 13def build_back(n):14    data = []15    for x in range(n):16        data.append(x)                 # at the end: nothing moves17    data.reverse()                     # reverse once at the end: n // 2 swaps18    return data, n // 219 20a, m1 = build_front(400)21b, m2 = build_back(400)22print(a == b, a[:5])23print("insert at front:", m1)24print("append, then reverse:", m2)
Output
True [399, 398, 397, 396, 395]
insert at front: 79800
append, then reverse: 200

0 + 1 + 2 + … + 399 = 79800: double n and the moves go up four times.

Guess the outputA wrong guess is fine

After these three steps, what does it print?

1a = [1, 2, 3, 4, 5]2a.insert(2, 9)3a.pop(0)4a.insert(-1, 7)5print(a)

How many move on average: if inserting at each of the n + 1 places 0 to n is equally likely, on average (0 + 1 + … + n) / (n + 1) = n/2 elements move; deleting at 0 to n − 1 moves (n − 1)/2 on average. So insert and delete are both O(n), while reading by index is O(1).

A favourite exam question: "insert at the i-th position" usually counts i from 1 (the position number), which is Python index i − 1. Average moves: n/2 for insert, (n − 1)/2 for delete.

Choose one

In a table of length n, how many elements move when you insert at the i-th position (counting from 1)?

Removing every copy of a value: one pass

To remove every 3 from a list, the handy way is while 3 in a: a.remove(3). Each remove searches from the front and then moves the rest, so k threes cost k passes of O(n).

One pass is enough: i looks from front to back, and k says "where the next item to keep goes". Anything that is not a 3 is copied to a[k], and k moves on one. i is always ahead of k (or on the same slot), so nothing not yet looked at gets overwritten.

a313435012345↑i↑k
1k = 02for i in range(len(a)):3    if a[i] != x:4        a[k] = a[i]5        k += 16del a[k:]

Removing every 3: i looks at each item, those to keep are copied to a[k] and k moves on; finally everything after k is cut off

Write both versions by hand and count the work (each comparison or move counts 1):

main.py
1def remove_all_slow(a, x):2    work = 03    while True:4        pos = -15        for i in range(len(a)):        # find the first x from the front6            work += 17            if a[i] == x:8                pos = i9                break10        if pos < 0:11            return work12        for i in range(pos, len(a) - 1):   # move the rest forward13            a[i] = a[i + 1]14            work += 115        a.pop()16 17def remove_all_fast(a, x):18    work = 019    k = 020    for i in range(len(a)):21        work += 122        if a[i] != x:23            a[k] = a[i]24            k += 125    del a[k:]26    return work27 28a = [3, 1] * 20029b = [3, 1] * 20030print("remove loop:", remove_all_slow(a, 3))31print("k pointer:", remove_all_fast(b, 3))32print(a == b, len(a))
Output
remove loop: 60300
k pointer: 400
True 200

In interviews: "Remove element in place", "Move zeroes" and "Remove duplicates from a sorted array" are all this k pointer. "Why doesn't a BFS queue use list.pop(0)?" Every dequeue moves n − 1 items; use a deque.

Guess the outputA wrong guess is fine

The k pointer runs to the end, but without del a[k:]. What does it print?

1a = [3, 1, 3, 4, 3, 5, 3, 2]2k = 03for i in range(len(a)):4    if a[i] != 3:5        a[k] = a[i]6        k += 17print(k, a)
Choose one

Remove every 2 from [2, 7, 2, 2, 5, 7] with the k pointer. What is k at the end, and what are the first k slots?

Exercise 2

Move the zeroes to the end

Finish move_zeroes(a): move every 0 to the end in place, keeping the other numbers in their order. One pass: k says where the next non-zero number goes.

It should print
[1, 3, 12, 0, 0]
[1, 0, 0]
exercise2.py
1def move_zeroes(a):2    k = 03    # first pass: copy non-zeros to a[k]; then fill everything from k on with 04    pass5 6a = [0, 1, 0, 3, 12]7move_zeroes(a)8print(a)9b = [0, 0, 1]10move_zeroes(b)11print(b)
Output
Press Run or Ctrl+Enter

How you write it at work

  • In and out at the end only: a list is enough. append and pop() are both O(1); it is a stack.
  • In and out at both ends: use collections.deque, where appendleft and popleft are O(1) too. The price is that getting something in the middle by index, d[i], becomes O(n).
  • Removing many items: a[:] = [v for v in a if v != x] is one O(n) pass; it takes a[:] to change the list in place so other names see it.
  • Removing a slice: del a[i:j] moves the rest once; do not pop(i) in a loop.
  • Building it backwards: append and then a.reverse(), rather than insert(0, x) again and again.
main.py
1from collections import deque2 3q = deque([1, 2, 3])4q.appendleft(0)5q.append(4)6print(q.popleft(), q.pop())7print(list(q))8 9a = [3, 1, 3, 4, 3, 5]10a[:] = [v for v in a if v != 3]11print(a)12 13b = list(range(10))14del b[2:8]15print(b)
Output
0 4
[1, 2, 3]
[1, 4, 5]
[0, 1, 8, 9]
Guess the outputA wrong guess is fine

Every 3 is removed with a[:] = …. What do you see through b?

1a = [3, 1, 3, 4]2b = a3a[:] = [v for v in a if v != 3]4print(b)

Summary

Take-away

Inserting and deleting in a list: the further from the end, the more moves

  • insert(i, x) moves everything after i back: n − i items
  • pop(i) and del a[i] move everything after forward: n − 1 − i items
  • append and pop() work at the end and move nothing: O(1)
  • n inserts at the front in a loop make n(n − 1)/2 moves: append, then reverse
  • Both ends: deque; removing many: a comprehension or a k pointer, in one pass
  • Inserting moves back to front, deleting moves front to back; insert positions are 0 to size, delete 0 to size − 1
1a.append(x); a.pop()        # O(1)2a.insert(0, x); a.pop(0)    # O(n)3q.appendleft(x); q.popleft()  # deque: O(1)4a[:] = [v for v in a if v != x]