union of n sets in python by R4R Team

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

Syntax-

set1.union(set2).union(set3).union(set4)......union(set-n)

Example

set1 is {1,2,3}
set2 is {3,4,5}
set3 is {"one","two","three"}
union is {1,2,3,4,5,"one","two","three"}


program-

set1={1,2,3,4}
set2={3,4,5,6,7,8,9}
set3={"one","two","three"}
set4={'a','b','c'}

print("Set1 is",set1)
print("Set2 is",set2)
print("Set3 is",set3)
print("Set4 is",set4)

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

union=set1 | set2 | set3 | set4
print(union)


output-

Set1 is {1, 2, 3, 4}
Set2 is {3, 4, 5, 6, 7, 8, 9}
Set3 is {'one', 'three', 'two'}
Set4 is {'b', 'c', 'a'}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 'three', 'b', 'one', 'c', 'two', 'a'}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 'three', 'b', 'one', 'c', 'two', 'a'}


-In this program, we try to find the union of four sets by two methods, firstly by union() function and secondly by '|' operator.




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!