Skip to main content

Section 9.7 Deleting elements

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:
pop modifies the list and returns the element that was removed. If you don't provide an index, it deletes and returns the last element.

Checkpoint 9.7.1.

    Q-2: What is printed by the following statements?
    alist = [4, 2, 8, 6, 5]
    temp = alist.pop(2)
    temp = alist.pop()
    print(alist)
    
  • [4, 8, 6]
  • pop(2) removes the item at index 2, not the 2 itself.
  • [2, 6, 5]
  • pop() removes the last item, not the first.
  • [4, 2, 6]
  • Yes, first the 8 was removed, then the last item, which was 5.

Checkpoint 9.7.2.

    Q-3: What is printed by the following statements?
    alist = [4, 2, 8, 6, 5]
    alist = alist.pop(0)
    print(alist)
    
  • [2, 8, 6, 5]
  • alist is now the value that was returned from pop(0).
  • [4, 2, 8, 6, 5]
  • pop(0) changes the list by removing the first item.
  • 4
  • Yes, first the 4 was removed from the list, then returned and assigned to alist. The list is lost.
  • None
  • pop(0) returns the first item in the list so alist has now been changed.
If you don't need the removed value, you can use the del operator:
If you know the element you want to remove (but not the index), you can use remove:
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
As usual, the slice selects all the elements up to, but not including, the second index.

Checkpoint 9.7.3.

    Q-7: What is the value of alist after the following code executes?
    alist = ['a', 'b', 'c', 'd', 'e', 'f']
    del alist[1:5]
    print(alist)
    
  • ['a', 'b', 'c', 'd', 'e', 'f']
  • The del method removes part of the list, so it will be shorter.
  • ['a', 'f']
  • 'a' is the 0th element of the list and 'f' is the 5th element of the list, so these are the values that remain after deleting [1:5].
  • ['f']
  • Remember that lists start at 0, not 1, and that a slice stops before the second element - not after.
  • ['b', 'c', 'd', 'e']
  • These are the values that will be deleted with the slice [1:5]

Checkpoint 9.7.4.