0% completed
Sets in Python are mutable, allowing elements to be added or removed dynamically. However, since sets do not maintain order, elements cannot be modified directly like lists. Instead, Python provides methods for adding and removing elements efficiently.
The most commonly used methods are:
add()
– Adds a single element to the set.update()
– Adds multiple elements from another iterable.discard()
– Removes an element safely without causing an error.The add()
method allows adding one element to a set.
num_set.add(4)
adds 4
to the set.4
already exists, the set remains unchanged.The update()
method allows adding multiple elements from a list, tuple, or another set.
num_set.update([5, 6, 7])
adds multiple elements at once.The discard()
method removes an element without causing an error if the element is missing.
discard(20)
removes 20
from the set.discard(60)
does nothing since 60
is not in the set, but no error is raised.Python provides efficient methods to modify sets dynamically. These methods allow efficient modification of sets while preventing unnecessary errors.
.....
.....
.....