Python language basics 50: adding new elements to a set


In the previous post we started looking at how sets are represented in Python. We saw how sets are meant to contain unique objects. Sets are not allowed to have duplicates, i.e. two objects with the same value. Duplicates are filtered out when constructing a set.

In this post we’ll see 2 ways to add elements to an already existing set.

Adding objects to sets

Consider the following set:

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

Adding a new capital to the set can be done through the add method:


Do not assume anything about the order in which the elements are added into the set. When printing or iterating the set you can get very different results, e.g.

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

…which is definitely not the same order as they appear in the original declaration.

The add function has no effect if you try to add a non-unique element:


The value is simply ignored.

Adding more than one element to the set can be achieved with the update method. This method accepts another collection which can be converted into a set, such as a list or a tuple. Non-unique elements are ignored. Here’s an example with a list:

capitals = {"Stockholm", "Budapest", "Helsinki", "Copenhagen", "Oslo", "Paris"}
new_capitals = ["Athens", "Helsinki", "Madrid", "Tirana", "Oslo", "Belgrade"]

Capitals will contain…

{‘Paris’, ‘Budapest’, ‘Tirana’, ‘Madrid’, ‘Athens’, ‘Oslo’, ‘Stockholm’, ‘Copenhagen’, ‘Helsinki’, ‘Belgrade’}

Here’s another example with integers and a tuple:

years = {1985, 1986, 1987, 1988, 1989}
new_years = (1987, 1988, 1989, 1990, 1991, 1992)

‘years’ will hold…

{1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992}

In the next post we’ll see how to remove objects from a set.

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: