To add element inside set there are two built-in function
1. add()
2. update()
- To add one item to a set use the add() method.
- The set add() method adds a given element to a set if the element is not present in the set Syntax:
setname.add(element)
Example:
color={"red","green","blue"}
#add new element "black" to set
color.add("black")
print(color)
Output:
{"red","green","black","blue"}
- If the element is alredy present in the set then it will not added again to set , because set do not contain any duplicate value.
Example:
color={"red","green","blue"}
#add new element "blue" to set
color.add("blue")
print(color)
Output:
{"red","green","blue"}
- Add multiple items to a set, using the update() method Syntax:
setname.update(iterable object)
Example:
color={"red","green","blue"}
#Add "black" and "orange" to set
color.update(["black","orange"])
print(color)
Output:
{'orange', 'red', 'green', 'blue', 'black'}
To remove an element from set there are following built-in function
1. remove()
2. discard()
3. pop()
- remove() method removes the element from the set only if the element is present in the set.
- If the element is not present in the set, then an error or exception is raised.
Example:
color={"red","green","blue"}
#remove "red"
color.remove("red")
print(color)
Output:
{"green","blue"}
Example:
color={"red","green","blue"}
#remove "black"
color.remove("black")
Output:
KeyError: 'black'
- discard() method removes the element from set only if the element is present in the set.
- If the element is not present in the set, then no error or exception is raised.
Syntax:
setname.discard(element)
Example:
color={"red","green","blue"}
#remove "black"
color.remove("black")
Output:
#Result:KeyError:{"red","green","blue"}
- pop() removes any orbitary elemnt and return it. Example:
color={"red","green","blue"}
color.pop()
print(color)
Output:
{'red', 'green'}
- Once a set is created, you cannot change its items.