Course
Join Sets
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Join Sets
In Python, a Set is an ordered collection of items. The items may be of different types. However, an item in the set must be an immutable object. It means, we can only include numbers, string and tuples in a set and not lists. Python's set class has different provisions to join set objects.
Using the "|" Operator
The "
|
" symbol (pipe) is defined as the union operator. It performs the A∪B operation and returns a set of items in A, B or both. Set doesn't allow duplicate items.s1={1,2,3,4,5}s2={4,5,6,7,8}s3 = s1|s2print (s3)
It will produce the following output
{1, 2, 3, 4, 5, 6, 7, 8}
Using the union() Method
The set class has
union()
method that performs the same operation as |
operator. It returns a set object that holds all items in both sets, discarding duplicates.s1={1,2,3,4,5}s2={4,5,6,7,8}s3 = s1.union(s2)print (s3)
Using the update() Method
The
update()
method also joins the two sets, as the union()
method. However it doen't return a new set object. Instead, the elements of second set are added in first, duplicates not allowed.s1={1,2,3,4,5}s2={4,5,6,7,8}s1.update(s2)print (s1)
Using the unpacking Operator
In Python, the "
*
" symbol is used as unpacking operator. The unpacking operator internally assign each element in a collection to a separate variable.s1={1,2,3,4,5}s2={4,5,6,7,8}s3 = {*s1, *s2}print (s3)
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.