FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set add() Method with examples




Python Set add() method is used to add an element to a Set. Since Set doesn't allow duplicates, if you try to add an already existing element to a Set, it won't do anything.

Set add() Method Syntax

set.add(item)

Here item is the element that we want to add to Set.

Set add() method Example

In the following example we have a Set myset and we are adding an element to the Set myset using add() method.

# Set add() method example

myset = {1, 2, "hello", 5, "bye"}

# displaying set before adding any element
print(myset)

#adding an element to a the Set myset
myset.add("noidatut")

# displaying set after adding an element
print(myset)

Example 2: Adding a tuple to a Set using add() method

In the following example, we have a Set myset and a tuple t1 and we are adding the tuple t1 to the Set myset. Similar to the elements, if we try to add an already existing tuple to a set then it won't add it and it won't raise any error.

# A Set
myset = {1, 2, "hi"}

# A tuple
t1 = (10, 20, "hello")

# displaying set before adding the tuple
print(myset)

#adding the tuple t1 to the set myset
myset.add(t1)

# displaying set after adding the tuple t1
print(myset)






Leave Comment