Python set is an unordered, unindexed, unchangeable data type that is used to store multiple unique values in a single variable. You can add or remove items from a set, but you can’t change the order of the items.
Adding an Item to the Set
You can add or append an item to an existing python set easily using the built-in add() method. It will add only unique values.
languages = {'English', 'German', 'Italian'}
new_item = 'French'
languages.add(new_item)
print(languages) # {'Italian', 'German', 'English', 'French'}
How to Combine Two Different Python Sets?
We can combine sets using the update() method. This method adds the items of the second set to the first set.
languages_set_1 = {'English', 'German', 'Italian'}
languages_set_2 = {'Dutch', 'Polish', 'Tamil'}
languages_set_1.update(languages_set_2)
print(languages_set_1) # {'Italian', 'Polish', 'German', 'English', 'Tamil', 'Dutch'}
How to Add Two Sets Without Changing The Existing Set?
We can use the logical “or” operator to add two sets and store them in a new variable. This method is used to create a new set without modifying the values of the existing sets.
languages_set_1 = {'English', 'German', 'Italian'}
languages_set_2 = {'Dutch', 'Polish', 'Tamil'}
languages_set_3 = languages_set_2 | languages_set_1
print(languages_set_3) # {'Italian', 'Polish', 'German', 'English', 'Tamil', 'Dutch'}