Python

add method in set

Click for All Topics

add method in set - Python

  • Add method is used to add elements in an empty set.
  • When we call the add method we pass an element as an argument.
  • Python calculates the hash code for that element using the hash function, if an element with the same hash code is already present in a set then it does not add the element.
  • We can not pass mutable data types(e.g. list, tuple, etc.) as an argument of the add method.
  • Add takes exactly one argument which means we can add only one element at one time.
  • The time complexity of the add method is constant or O(1).

Syntax –

set_name.add(element)

  • element → It is a required argument, we have to pass one element each time when we call add method.

Example 1 – let’s see an example

				
					my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set)
# Output - 
# {1,2,3}
				
			
  • In the above example, first we create an empty set using the set function and store it in the my_set variable.
  • After creating an empty set first we add 1 in my_set using the .add() method.
  • After adding 1 we also add 2 and 3 in my_set.
  • After that print my_set using the print() function.
Example 2-
				
					my_set2={10,20,30}
my_set2.add(40)
my_set2.add(20)
print(my_set2)

# Output-
# {40, 10, 20, 30}
				
			
  • In the above example, we see that we couldn’t add ’20’ in my_set2 because 20 is already present in my_set2.
Example 3-
				
					my_set3={'this','is','edSlash'}
my_set3.add('Hello')
print(my_set3)
my_set3.add('anurag','dubey')  #will give an error think about it.

# Output - 
# {'Hello','this','is','edSlash'} # may be your output in a different order
# Traceback (most recent call last):
  # File "/home/main.py", line 4, in <module>
    # my_set3.add('anurag','dubey')  
# TypeError: set.add() takes exactly one argument (2 given)
				
			
  • In the above example, line 4 gives an error because we passed two arguments to the add method.
  • You can use the update method to add multiple elements in a set at one time.
Example 4-
				
					my_set4={'a','b','c','d'}
my_set4.add(('e','f','g'))
print(my_set4)

# Output -
# {'a', ('e', 'f', 'g'), 'c', 'd', 'b'}
				
			
Example 5-
				
					my_set5 = set()
for i in range(1, 6):
    my_set5.add(i)
print(my_set5) 

# Output -
# {1,2,3,4,5}
				
			
  • In the above example, we see that we can also add elements in a set using the for loop method.