Python language basics 42: 2 ways to remove elements from a collection


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’ 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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: