Joining Sets in Python: Combining Multiple Sets

thumb_up 1  ·  sell Python set joining, Combining sets in Python, Merging multiple sets in Python

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|s2 print (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)
 
 
 
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back