How to Add Values to a Set in Python


In this example we will show how to create a set and add values to it in Python.

2. Create a Set

We can create a set as follows:

s = {value01, value02,...}
or
set(value)

3. Add Element

We can add the element x to the set s using the following method, and if x already exists, s will not be updated:

s.add( x )

Here is an example:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

testset = set(("Google", "Yahoo", "Amazon"))
# add a new value
testset.add("Facebook")
print(testset)

# add an existing value
testset.add("Google")
print(testset)

Output:

{'Google', 'Yahoo', 'Amazon', 'Facebook'}

{'Google', 'Yahoo', 'Amazon', 'Facebook'}

4. Remove Element

We can remove the element x from the set s using the following method, and if x does not exist, it will show an error:

s.remove( x )

Here is an example:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

thisset = set(("Google", "Yahoo", "Facebook"))
thisset.remove("Yahoo")
print(thisset)
{'Google', 'Facebook'}
thisset.remove("Yahoo")

Output:

{'Google', 'Facebook'}
KeyError: 'Yahoo'
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments