Python Programming
About Lesson

Add Items
We cannot update or change the existing values of a set but can add new data elements. The place of the newly inserted data element cannot be determined since set is unordered.
The following ways can be used to add new data items to Set:
1. Using add() function: to add a single data element
2. Using update() function: to add more than one data items

#Example to add an item to a set, using the add() method
fruits = {“apple”, “banana”, “cherry”}
fruits.add(“orange”)
print(fruits)

#Example to add multiple items to a set, using the update() method
fruits = {“apple”, “banana”, “cherry”}
fruits.update([“orange”, “mango”, “grapes”])
print(fruits)

The len() method can be used with Set to know the number of set elements.

#Example to get the number of items in a set
fruits = {“apple”, “banana”, “cherry”}
print(len(fruits))

Remove Item
The existing data items of Set can be removed by the following methods:
1. Using remove() method: raises an error if the items removable is not exists
2. Using discard() method: don’t raise any error if the removable item is not present
3. Using pop() method: always remove the last element but cannot say which item will get removed since set is unordered. This method also returns the removed item.
4. Using clear() method: empty the set
5. Using del keyword: removes set from memory

#Example code to remove “banana” by using the remove() method
fruits = {“apple”, “banana”, “cherry”}
fruits.remove(“banana”)
print(fruits)

#Example code to remove “banana” by using the discard() method
fruits = {“apple”, “banana”, “cherry”}
fruits.discard(“banana”)
print(fruits)

#Example code to remove the last item by using the pop() method
fruits = {“apple”, “banana”, “cherry”}
x = fruits.pop()
print(x)
print(fruits)

#Example code to use clear() method to empty the set
fruits = {“apple”, “banana”, “cherry”}
fruits.clear()
print(fruits)

#Example code to use del keyword will delete the set completely
fruits = {“apple”, “banana”, “cherry”}
del fruits
print(fruits)

Join Two Sets
Joining of sets means creating a new set containing all the elements of given sets or add elements of one set to another. In any case, the resultant set won’t have any duplicate values. Two or more sets can be joined using the following way:
1. Using union() method: creates a new set by containing all items from joining sets
2. Using update() method: adds elements of one set to another.

#Example code to use union() method returns a new set with all items from both sets
set1 = {“a”, “b” , “c”}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

#Example code to use update() method inserts the items in set2 into set1
set1 = {“a”, “b” , “c”}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

You cannot copy content of this page