C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Set add() MethodPython add() method adds new element to the set. It takes a parameter, the element to add. It returns None to the caller. The method signature is given below. Signatureadd(elem) Parameterselem: element to be added. ReturnIt returns None. Let's see some examples of add() method to understand it's functionality. Python Set add() Method Example 1A simple example to add a new element in the set. It returns a modified set. # Python set add() Method # Creating a set set = {1,2,3} # Displaying elements print(set) # Calling method set.add(4) # Adding new element # Displaying elements print("After adding new element: \n",set) Output: {1, 2, 3} After adding new element: {1, 2, 3, 4} Python Set add() Method Example 2Adding an element which already exist will not modifiy the set. Set does not store duplicate elements. See the example below. # Python set add() Method # Creating a set set = {1,2,3} # Displaying elements print(set) # Calling method set.add(2) # Adding duplicate element # Displaying elements print("After adding new element: \n",set) Output: {1, 2, 3} After adding new element: {1, 2, 3} Python Set add() Method Example 3Set also allows to store other datastructures like tuple, list etc. See the example below. # Python set add() Method # Creating a set set = {1,2,3} # Displaying elements print(set) tup = (4,5) # Creating tuple # Calling method set.add(tup) # Adding tuple to the set # Displaying elements print("After adding new element: \n",set) dup = (2,3,4) set.add(dup) # Adding duplicate using tuple print("After adding tuple: \n",set) Output: {1, 2, 3} After adding new element: {(4, 5), 1, 2, 3} After adding tuple: {1, 2, 3, (4, 5), (2, 3, 4)}
Next TopicPython Set
|