Add/Remove Set Items
Add items to set:
If you want to add a single item to the set use the add()
method.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)
Output:
{'Tokyo', 'Helsinki', 'Madrid', 'Berlin', 'Delhi'}
If you want to add more than one item, simply create another set or any other iterable object (list, tuple, dictionary), and use the update()
method to add it into the existing set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Helsinki", "Warsaw", "Seoul"}
cities.update(cities2)
print(cities)
Output:
{'Seoul', 'Berlin', 'Delhi', 'Tokyo', 'Warsaw', 'Helsinki', 'Madrid'}
Remove items from set:
We can use remove()
and discard()
methods to remove items from a set.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)
Output:
{'Delhi', 'Berlin', 'Madrid'}
Example 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.discard("Delhi")
print(cities)
Output:
{'Berlin', 'Tokyo', 'Madrid'}
The main difference between remove
and discard
is that, if we try to delete an item which is not present in the set, then remove()
raises an error, whereas discard()
does not raise any error.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Seoul")
print(cities)
Output:
KeyError: 'Seoul'
Example 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.discard("Seoul")
print(cities)
Output:
{'Madrid', 'Delhi', 'Tokyo', 'Berlin'}
There are various other methods to remove items from the set: pop()
, del
, clear()
.
pop():
This method removes the last item of the set but the catch is that we don’t know which item gets popped as sets are unordered. However, you can access the popped item if you assign the pop()
method to a variable.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)
Output:
{'Tokyo', 'Delhi', 'Berlin'}
Madrid
del:
del
is not a method, rather it is a keyword which deletes the set entirely.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
Output:
NameError: name 'cities' is not defined
We get an error because our entire set has been deleted and there is no variable called cities
which contains a set.
What if we don’t want to delete the entire set, we just want to delete all items within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)
Output:
set()
Check if item exists
You can also check if an item exists in the set or not.
Example 1:
info = {"Carla", 19, False, 5.9}
if "Carla" in info:
print("Carla is present.")
else:
print("Carla is absent.")
Output:
Carla is present.
Example 2:
info = {"Carla", 19, False, 5.9}
if "Carmen" in info:
print("Carmen is present.")
else:
print("Carmen is absent.")
Output:
Carmen is absent.