union of two sets in python by R4R Team

- union of two sets are the set which contain the elements of both given sets.
- In python, to find the union of two sets we have two method as follows-
- one is direct by union() function
- and another method is by '|' operator.

Syntax-

set1.union(set2)

Example

set1 is {1,2,3}
set2 is {3,4,5}
union is {1,2,3,4,5}


program-

set1={1,2,3,4}
set2={3,4,5,6,7,8,9}

print("Set1 is",set1)
print("Set2 is",set2)

union=set1.union(set2)
print(union)

union=set2.union(set1)
print(union)

union=set1 | set2
print(union)

union=set2 | set1
print(union)


output-

Set1 is {1, 2, 3, 4}
Set2 is {3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9}


-In this program, we have two sets {1,2,3,4} and {3,4,5,6,7,8,9} then union of both sets is {1,2,3,4,5,6,7,8,9}




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!