
Python set - Add the value to a set
You can add an item to a set using add()
.
s = {'a', 'b'}
s.add('c')
print(s) # {'c', 'b', 'a'}
A Python set has no order so the result of print() changes at random. This function returns None.
s = {'a', 'b'}
t = s.add('c')
print(s) # {'c', 'b', 'a'}
print(t) # None
Add an element that already exists in the Python set
s = {'a', 'b'}
t = s.add('a')
print(s) # {'b', 'a'}
Adding the value that already exists doesn't change the set.
Union sets in Python
s = {'a', 'b'}
t = {'c', 'd'}
u = s | t
print(u)
# {'d', 'b', 'a', 'c'}
In python, |
symbol means set union and more than two sets can be united by |
.
s = {'a', 'b'}
t = {'c', 'd'}
u = {'Java', 'Python'}
w = s | t | u
print(w)
# {'Python', 'b', 'a', 'c', 'd', 'Java'}
add()
returns None and |
returns new set.
update()
s1 = {'a', 'b'}
s2 = {'a', 'b'}
s1.update('c')
s2.update({'c'})
print(s1) # {'b', 'c', 'a'}
print(s2) # {'b', 'c', 'a'}
update()
can substitute add()
in some cases.
Add None
s = {1, 2, 3, 4}
s.add(None)
print(s) # {1, 2, 3, 4, None}
Comments
Powered by Markdown