Adding and Deleting elements - set¶
Let us see how we can add and delete elements to the set in Python.
We can add elements to
set
or update existing ones.add
update
union
We can delete elements from the
set
using different functions.pop
remove
discard
clear
s = {1, 2, 3, 3, 3, 4, 4}
s.add(5)
s
{1, 2, 3, 4, 5}
s.update?
Docstring: Update a set with the union of itself and others.
Type: builtin_function_or_method
s.update({4, 5, 6, 7}) # Updates the set on which update is invoked
s
{1, 2, 3, 4, 5, 6, 7}
s.union?
Docstring:
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Type: builtin_function_or_method
s = {1, 2, 3, 4, 5}
s.union({4, 5, 6, 7}) # Creates new set
{1, 2, 3, 4, 5, 6, 7}
s
{1, 2, 3, 4, 5}
s.pop?
Docstring:
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
Type: builtin_function_or_method
s.pop()
1
s
{2, 3, 4, 5}
s.remove?
Docstring:
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
Type: builtin_function_or_method
s.remove(4)
s
{2, 3, 5}
s.remove(6) # 6 does not exist, throws KeyError
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-17-b3638b2cbd97> in <module>
----> 1 s.remove(6) # 6 does not exist, throws KeyError
KeyError: 6
s = {1, 2, 3, 4, 5}
s.discard?
Docstring:
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
Type: builtin_function_or_method
s.discard(4)
s
{1, 2, 3, 5}
s.discard(6)
s
{1, 2, 3, 5}
s.clear?
Docstring: Remove all elements from this set.
Type: builtin_function_or_method
s.clear()
s
set()