Python Set union() Method

A.union(B) returns a new set containing all distinct elements from the inputs. The | operator is the set-to-set equivalent; duplicates are naturally stored only once.

union() can accept iterable arguments, whereas | requires set-like operands. If you want to change an existing set instead, use update(). See the Set operations overview.

Set order: sets are unordered. Whenever an example prints a set, the displayed element order can differ between runs or Python environments.

  • Video Tutorial on Set


union using | operator

set operation union All distinct elements from both sets
Using the vertical bar (|) operator
A={1,2,3}
B={3,4,5}
print(A|B)
Output ( Note 3 is used once only )
{1, 2, 3, 4, 5}
Using union() method
A={'a','b','c'}
B={'a','y','z'}
print(A.union(B))
Output
{'z', 'c', 'a', 'y', 'b'}

Using More Than Two Sets

We can use any number of sets with union()
A={'a','b','c'}
B={'a','y','z'}
C={'a','k','l'}
print(A | B |C)
Output
{'z', 'l', 'k', 'c', 'a', 'y', 'b'}

union() method

Using string ( iterable object ) with union() method
A={'a','b','c','x','y'}
B='Alex'
print(A.union(B))
Output
{'l', 'e', 'A', 'a', 'c', 'x', 'y', 'b'}
Using list with union() method.
A={'a','b','c'}
B=['a','x','y']
print(A.union(B))
Output
{'c', 'x', 'y', 'a', 'b'}
Below code will generate error.
print(A | B)
 TypeError: unsupported operand type(s) for |: 'set' and 'list'
All Set Methods Set Operations Questions with solutions on set
intersection() difference() symmetric_difference()


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer