Add To Set Python
Chapter:
Python
Last Updated:
05-10-2018 13:07:21 UTC
Program:
/* ............... START ............... */
animals = {"cat","dog"}
animals.add("Lion")
animals.add("Lion") # You cannot add duplicate entry to set.
print(animals)
animals.add("Elephant")
print(animals)
# By using the update method you can add multiple elements at a time.
animals.update(["Rabbit","Wolf","giraffe"])
print(animals)
/* ............... END ............... */
Output
{'Lion', 'dog', 'cat'}
{'Lion', 'dog', 'cat', 'Elephant'}
{'cat', 'Lion', 'dog', 'giraffe', 'Elephant', 'Wolf', 'Rabbit'}
Notes:
-
By using add method in python, we can add a new entry to set. Set will store unique entry only in the above program you can see that lion is adding two times, but when printing it will print only one lion.
- If the element already exists, the add() method does not add the element.
- By using add method in python, you can add only one entry at a time, but by using update method you can add more than one element at a time. Kindly refer program example for clarification.