Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Set union() Method

Python Set union() Method

Python3 Lists Python Sets


Description

The union() method returns the union of two sets, that is, it contains the elements of all sets, with duplicate elements appearing only once.

Syntax

Syntax of the union() method:


set.union(set1, set2...)

Parameters

Return Value

Returns a new set.

Example

Merge two sets; duplicate elements appear only once:

Example 1

x

= {

"

apple

"

,

"

banana

"

,

"

cherry

"

}

y

= {

"

google

"

,

"

runoob

"

,

"

apple

"

}

z

=

x

.

union

(

y

)

print

(

z

)

The output is:


{'cherry', 'runoob', 'google', 'banana', 'apple'}

Merge multiple sets:

Example 1

x

= {

"

a

"

,

"

b

"

,

"

c

"

}

y

= {

"

f

"

,

"

d

"

,

"

a

"

}

z

= {

"

c

"

,

"

d

"

,

"

e

"

}

result

=

x

.

union

(

y

,

z

)

print

(

result

)

The output is:


{'c', 'd', 'f', 'e', 'b', 'a'}

Python3 Lists Python Sets