Python Set add() Method
Python Set add() Method
The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it.
Syntax
set.add(element)
Parameter
element- This parameter represents the element that is to be added to the set.
Return
None
Example 1
# Python program explaining # the set.add() method # initializing the set fruits = {"watermelon", "banana", "apple"} print("Actual set: ",fruits) # adding the more fruits in the set fruits.add("orange") fruits.add("grapes") # After adding the more fruits in the set print("New set: ",fruits)
Output
Actual set: {'apple', 'watermelon', 'banana'} New set: {'apple', 'watermelon', 'orange', 'banana', 'grapes'}
Example 2
# Python program explaining # the set.add() method # set of week week = {'Monday', 'Tuesday', 'Wednesday','Thursday'} # printing the set print('Week values:', week) # passing tuple values tupleVal = ('Friday', 'Saturday','Sunday') # adding tuple week.add(tupleVal) print("After adding tuple values...") print('Week values are:', week) # adding same tuple values again #the tuple elements are already present in the set, it doesn't add. print("Again adding the tuple values...") week.add(tupleVal) print('Week values are:', week)
Output
Week values: {'Monday', 'Thursday', 'Wednesday', 'Tuesday'} After adding tuple values... Week values are: {('Friday', 'Saturday', 'Sunday'), 'Monday', 'Thursday', 'Wednesday', 'Tuesday'} Again adding the tuple values... Week values are: {('Friday', 'Saturday', 'Sunday'), 'Monday', 'Thursday', 'Wednesday', 'Tuesday'}