Python Set add method with Example – Python Tutorial
3 months ago Lalit Bhagtani 0
In this tutorial, we will learn about python set add method.
add method :
This method is used to insert single immutable element ( passed as an argument ) in the set object. If we try to insert an element, which is already exist in the set object. It won’t insert that element again in the set. Element ( passed as an argument ) must be of immutable type like string, integer, float. If we try to insert a mutable type element like list, it will raises a TypeError.
Syntax : < Set Object >.add( < Immutable Object > )
# create empty set object and assign it to variable s s = set() # add element 1 in the set object s.add(1) # add element 2 in the set object s.add(2) # print all elements of set print(s) # add element 2 in the set object s.add(2) # print all elements of set print(s) # element 2 is not added second time # add list [1,2,3] in the set object s.add([1,2,3]) # TypeError is raised as list is not immutable type
That’s all for Python Set add method. If you liked it, please share your thoughts in comments section and share it with others too.