Python language basics 50: adding new elements to a set
September 26, 2015 Leave a comment
Introduction
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:
capitals.add("Madrid")
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:
capitals.add("Stockholm")
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.update(new_capitals)
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.update(new_years)
‘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.