Python language basics 42: 2 ways to remove elements from a collection
August 29, 2015 Leave a comment
Introduction
In the previous post we looked at a couple of ways to insert or append elements to a collection. We saw the usage of the insert, append and extend functions. We also discussed how the + and += operators affect a list.
In this post we’ll look at the exact opposite, i.e. how to remove an item from a collection.
Removing items from a Python collection
The del keyword
The first solution we’ll look at is the somewhat odd “del” keyword. It operates on collections but is not invoked in a function-like manner. Consider the following cities list:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]
Suppose you’d like to remove “Berlin”, i.e. the element at position 2 from the list. That will look like this with the del function:
del cities[2]
‘cities’ becomes…
[‘Stockholm’, ‘Budapest’, ‘Paris’, ‘Birmingham’, ‘Zürich’]
As strings are also collections you’d think the del keyword would work on those as well:
name = "Anngelina" del name[2]
This won’t work as strings are immutable.
Also, if you try to remove an element at a non-existent index, you’ll get an exception which we cannot handle yet:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"] del cities[100]
The above code will mercilessly fail.
The remove function
The del keyword works with indexes. The remove function on the other hand can be called directly on a collection and accepts an object. If the object is found in the collection then it is removed. Otherwise an exception is thrown which we cannot handle yet:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"] cities.remove("Zürich")
‘cities’ becomes…
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’]
In the next post we’ll take a look at the index method of collections to find the position of an element.
Read all Python-related posts on this blog here.