Python: Update Set

Once a set is created, we cannot change its items, but we can add new items in following ways:

By using add() method

We can add elements to the set by using built-in add() function. Only one element at a time can be added to the set by using add() method, loops are used to add multiple elements at a time with the use of add() method.

set_1 = set()
print("Blank Set:",set_1)

set_1.add(1)
set_1.add(2)
print("After adding two elements:",set_1)

for i in range(2,6):
    set_1.add(i)
    
print("After addition of elements from 2-6:",set_1)

Output:

Blank Set: set()
After adding two elements: {1, 2}
After addition of elements from 2-6: {1, 2, 3, 4, 5}

By using update() method:

For adding two or more elements update() method is used. This method accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases, duplicate elements are avoided.

Syntax:

set.update(set)

Example:

x = {"apple", "banana", "cherry","pineapple"}
y = {"a", "b", "c","d"}
x.update(y)
print(x)

Output:

{'c', 'banana', 'd', 'b', 'cherry', 'pineapple', 'a', 'apple'}
Tags