The add method
The add
method adds elements to a set. If the element is already in the set, it is not duplicated and the set remains in its original state. The element is added in an arbitrary order, its position for the set is not clearly defined. In the method parameter, we pass the element we want to add.
Syntax
set.add(what to add)
Example
Let's add a new element to our set:
st = {'a', 'b', 'c'}
st.add('e')
print(st)
Result of code execution:
{'e', 'b', 'c', 'a'}
Example
Now let's add an existing element:
st = {'a', 'b', 'c'}
st.add('b')
print(st)
After executing the code, we will get back our set:
{'b', 'a', 'c'}
See also
-
method
update
,
which adds elements from other sets -
method
remove
,
which removes elements from a set -
method
discard
,
which removes elements that are in the set -
method
pop
,
which removes the first element from a set -
function
len
,
which returns the length of the set -
function
frozenset
,
which creates an immutable set -
method
union
,
which unites sets