Python - Add Set Items



Even if a set holds together only immutable objects, set itself is mutable. We can add new items in it with any of the following ways −

Add Set Items

The add() method in set class adds a new element. If the element is already present in the set, there is no change in the set.

Syntax

set.add(obj)

Parameters

  • obj − an object of any immutable type.

Example

Take a look at the following example −

lang1 = {"C", "C++", "Java", "Python"}
lang1.add("Golang")
print (lang1)

It will produce the following output

{'Python', 'C', 'Golang', 'C++', 'Java'}

Add Sets Using update() Method

The update() method of set class includes the items of the set given as argument. If elements in the other set has one or more items that are already existing, they will not be included.

Syntax

set.update(obj)

Parameters

  • obj − a set or a sequence object (list, tuple, string)

Example

The following example shows how the update() method works −

lang1 = {"C", "C++", "Java", "Python"}
lang2 = {"PHP", "C#", "Perl"}
lang1.update(lang2)
print (lang1)

It will produce the following output

{'Python', 'Java', 'C', 'C#', 'PHP', 'Perl', 'C++'}

Add Any Sequence Object as Set Items

The update() method also accepts any sequence object as argument. Here, a tuple is the argument for update() method.

Example

lang1 = {"C", "C++", "Java", "Python"}
lang2 = ("PHP", "C#", "Perl")
lang1.update(lang2)
print (lang1)

It will produce the following output

{'Java', 'Perl', 'Python', 'C++', 'C#', 'C', 'PHP'}

Example

In this example, a set is constructed from a string, and another string is used as argument for update() method.

set1 = set("Hello")
set1.update("World")
print (set1)

It will produce the following output

{'H', 'r', 'o', 'd', 'W', 'l', 'e'}

Combine Unique Set Items

The union() method of set class also combines the unique items from two sets, but it returns a new set object.

Syntax

set.union(obj)

Parameters

  • obj − a set or a sequence object (list, tuple, string)

Return value

The union() method returns a set object

Example

The following example shows how the union() method works −

lang1 = {"C", "C++", "Java", "Python"}
lang2 = {"PHP", "C#", "Perl"}
lang3 = lang1.union(lang2)
print (lang3)

It will produce the following output

{'C#', 'Java', 'Perl', 'C++', 'PHP', 'Python', 'C'}

Example

If a sequence object is given as argument to union() method, Python automatically converts it to a set first and then performs union.

lang1 = {"C", "C++", "Java", "Python"}
lang2 = ["PHP", "C#", "Perl"]
lang3 = lang1.union(lang2)
print (lang3)

It will produce the following output

{'PHP', 'C#', 'Python', 'C', 'Java', 'C++', 'Perl'}

Example

In this example, a set is constructed from a string, and another string is used as argument for union() method.

set1 = set("Hello")
set2 = set1.union("World")
print (set2)

It will produce the following output

{'e', 'H', 'r', 'd', 'W', 'o', 'l'}
Advertisements