Python language basics 51: removing elements from a set

Introduction

In the previous post we discussed how to add new elements to an existing set. You can use the add method to add a single new element. The update function helps you insert multiple values at once. Both methods gracefully ignore duplicates, the set is guaranteed to only hold unique values.

In this post we’ll look at the opposite operation, i.e. how to remove objects.

Removing objects from a set

Consider the following set:

capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}

Let’s say you want to remove Oslo. The remove method is a straightforward solution:

capitals.remove("Oslo")

‘capitals’ will become…

{‘Budapest’, ‘Paris’, ‘Copenhagen’, ‘Helsinki’, ‘Stockholm’}

…as expected.

Note, however, that the function results in an error if you try to remove an object which is not in the set:

capitals.remove("Washington")

This will result in a key error:

KeyError: ‘Washington’

We’ll see later on in the course how to handle such errors in code.

There’s another function called ‘discard’ which works in a similar way but ignores objects that do not exist in the set:

capitals.discard("Washington")

The above call will simply execute without raising the same error as above.

In general you can use the ‘remove’ method if you want to know whether the removal was successful, i.e. the element existed in the set to begin with. Use ‘discard’ if you don’t care: remove the element if it exists otherwise just continue.

In the next post we’ll discuss some useful methods related to set algebra.

Read all Python-related posts on this blog here.

Advertisement

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:

WordPress.com Logo

You are commenting using your WordPress.com 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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: