How To: Lists: Removing from


Removing from a list

Removing things from a list is similar to adding them; we use different tools, but we still often need to talk in terms of positions, and those positions still start at 0.

Removing an item by its position

If we know the position of the item we want to remove, we've got two options: the del command and the pop(..) command

Removing an item with the del command

The del command works to remove items from a list. (del is short for "delete.")

The code below will remove the element in position 0 from list l – in this case, the 1:

l = [1,2,3,4,5]
del l[0]
# l is now equal to [2,3,4,5]

We can also use del on a few elements at once, using the list-slicing commands we've learned:

l = [2,3,4,5]
del l[0:2]
# l is now equal to [4,5]

Removing an item with the pop(..) command

The pop(..) command "pops off" the element in the position of the number in the parentheses.

The code below will remove the element in position 3 from list n – in this case, the 'c':

n = ['a', 'b', 'c', 'd', 'e']
n.pop(3)
# n is now ['a', 'b', 'c', 'e']

Removing an element by its value

The remove(..) command removes whatever is in parentheses from the list.

m = [5,6,7,8,9]
m.remove(6)
# m is now [5, 7, 8, 9]

If that element shows up more than once, it only removes the first occurence of that element from the list.

m = [5,5,6,7,8,9]
m.remove(5)
# m is now [5, 6, 7, 8, 9]

If we try to remove something that isn't in the list, Python gives back a ValueError, which is its way of saying "Hey! I couldn't find the value you wanted, and now I don't know what to do!"

m = [5,7,8,9]
m.remove(0)

Challenge

Below, there's a console with a list called li that holds the numbers between 1 and 6. Use a combination of the techniques above to turn li into a list that holds only the evennumbers between 1 and 6.

# To start, li = [1, 2, 3, 4, 5, 6]
# After your code, li should be [2, 4, 6]