beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Python Set union() method with examples

By Chaitanya Singh | Filed Under: Python Tutorial

The Set union() method returns a new set with the distinct elements from all the given Sets. The union is denoted by ∪ symbol. Lets say we have a Set A: {1, 2, 3} and Set B: {2, 3, 4} then to find the union of these sets we can call this method either like this A.union(B) or B.union(A) and the returned set would contain the elements {1, 2, 3, 4}.

Set union() method Syntax

set.union(set1, set2,...)

Parameters: This method accepts sets as parameters.
Return value: This method returns a set with the distinct elements of all the sets.

Python Set union() method example

In the following example we have three sets and we are finding union of sets X & Y, X & Z and X, Y & Z using union() method. We can also use | operator to find the union of sets.

# Set X
X = {1, 2, 3}

# Set Y
Y = {2, 3, 4}

# Set Z
Z = {5, 6, 7}

print("X ∪ Y:", X.union(Y))
print("X ∪ Z:", X.union(Z))
print("X ∪ Y ∪ Z:", X.union(Y, Z))

Output:
Python union() method example

Finding union of sets using | operator

Lets take the same example that we have seen above, however here we will use the | operator instead of union() method to find the union of sets.

# Set X
X = {1, 2, 3}

# Set Y
Y = {2, 3, 4}

# Set Z
Z = {5, 6, 7}

print("X ∪ Y:", X|Y)
print("X ∪ Z:", X|Z)
print("X ∪ Y ∪ Z:", X|Y|Z)

Output:

X ∪ Y: {1, 2, 3, 4}
X ∪ Z: {1, 2, 3, 5, 6, 7}
X ∪ Y ∪ Z: {1, 2, 3, 4, 5, 6, 7}

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap