The Wayback Machine - https://web.archive.org/web/20241126182947/https://www.geeksforgeeks.org/python-set-operations-union-intersection-difference-symmetric-difference/
Open In App

Python set operations (union, intersection, difference and symmetric difference)

Last Updated : 18 Dec, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article demonstrates different operations on Python sets.
Examples:

Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}

Output :
 Union : [0, 1, 2, 3, 4, 5, 6, 8]
 Intersection : [2, 4]
 Difference : [8, 0, 6]
 Symmetric difference : [0, 1, 3, 5, 6, 8]

In Python, below quick operands can be used for different operations.

| for union.
& for intersection.
– for difference
^ for symmetric difference




# Program to perform different set operations
# as we do in  mathematics
  
# sets are define
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
  
# union
print("Union :", A | B)
  
# intersection
print("Intersection :", A & B)
  
# difference
print("Difference :", A - B)
  
# symmetric difference
print("Symmetric difference :", A ^ B)


Output:

('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))

Previous Article
Next Article

Similar Reads

Fernet (symmetric encryption) using Cryptography module in Python
Cryptography is the practice of securing useful information while transmitting from one computer to another or storing data on a computer. Cryptography deals with the encryption of plaintext into ciphertext and decryption of ciphertext into plaintext. Python supports a cryptography package that helps us encrypt and decrypt data. The fernet module o
3 min read
Set update() in Python to do union of n arrays
We are given n arrays of any size which may have common elements, we need to combine all these arrays in such a way that each element should occurs only once and elements should be in sorted order? Examples: Input : arr = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1], [2, 4, 1, 3]] Output : [1, 2, 3, 4, 5, 6, 7, 9] A simple solution for this prob
2 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Most Efficient Way To Find The Intersection Of A Line And A Circle in Python
To make an efficient algorithm to find the intersection of a line and a circle, we need to understand what lines and circles are and how we can mathematically represent and calculate them in Python. Prerequisites LineCirclesQuadratics EquationsSolving a Quadratic EquationQuadratic Formula/Sridharacharya FormulaMathematical ApproachTo find the inter
8 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Python | Intersection of two String
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings. There are various ways in Python, through which we can perform the Intersection of two strings. Method #1 : Naive Method Create an empty string and check for new occurrence of character common to both string a
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Python | Pandas TimedeltaIndex.intersection
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.intersection() function return a new Index with elements from the index that are common to both the indexes. This
2 min read
Python | Pandas Index.intersection()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the in
2 min read
Python | Sympy Line.intersection() method
In Sympy, the function intersection() is used to find the intersection with another geometrical entity. Syntax: Line.intersection(o) Parameters: o: Point or LinearEntity Returns: intersection: list of geometrical entities Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) l1 =
1 min read
Intersection of two dataframe in Pandas - Python
Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them. Syntax: pd.merge(df1, df2, how) Example 1: import pandas as pd # Creating Data frames df1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi'
1 min read
Python – Sympy Polygon.intersection() Method
In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or c
2 min read
Python | Intersection of two lists
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples: Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]Output :[
6 min read
Python PySpark - Union and UnionAll
In this article, we will discuss Union and UnionAll in PySpark in Python. Union in PySpark The PySpark union() function is used to combine two or more data frames having the same structure or schema. This function returns an error if the schema of data frames differs from each other. Syntax: dataFrame1.union(dataFrame2) Here, dataFrame1 and dataFra
3 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni
3 min read
Python | Pandas Index.union()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.union() function form the union of two Index objects and sorts if possible. The function follows behaves like a standard se
2 min read
Python | Pandas TimedeltaIndex.union()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.union() function is a specialized union for TimedeltaIndex objects. It combines overlapping ranges with the same D
2 min read
Python SQLAlchemy - Performing union with three queries
In this article, we will see how to perform a union of three queries using SQLAlchemy in Python. Since we are going to use MySQL in this post, we will also install a SQL connector for MySQL in Python. However, none of the code implementations changes with change in the database except for the SQL connectors. pip install pymysqlWe will use the sampl
4 min read
Weather Union API(Zamato) with Python
Weather Union provides powerful APIs for integrating live weather data into your applications. With a wide range of endpoints, you can access current weather data at specific locations. This guide will walk you through the various APIs offered by Weather Union and provide examples of how to use them in Python. What is Weather Union & Its Featur
3 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Find the union of two NumPy arrays
To find union of two 1-dimensional arrays we can use function numpy.union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays. Syntax: numpy.union1d(array1, array2) Note The arrays given in input are flattened if they are not 1-dimensional. Let's see examples of how to find union of tw
2 min read
How to union multiple dataframe in PySpark?
In this article, we will discuss how to union multiple data frames in PySpark. Method 1: Union() function in pyspark The PySpark union() function is used to combine two or more data frames having the same structure or schema. This function returns an error if the schema of data frames differs from each other. Syntax: data_frame1.union(data_frame2)
4 min read
PostgreSQL - UNION operator
The PostgreSQL UNION operator is a powerful tool used to combine result sets from multiple queries into a single result set. It helps in consolidating data from different sources, making it easier to analyze and report. From this article, we can better understand the UNION Operator in PostgreSQL SyntaxSELECT column_1, column_2FROM table_name_1UNION
3 min read
Python | Morphological Operations in Image Processing (Opening) | Set-1
Morphological operations are used to extract image components that are useful in the representation and description of region shape. Morphological operations are some basic tasks dependent on the picture shape. It is typically performed on binary images. It needs two data sources, one is the input image, the second one is called structuring compone
3 min read
Python | Morphological Operations in Image Processing (Closing) | Set-2
In the previous article, the Opening operator was specified which was applying the erosion operation after dilation. It helps in removing the internal noise in the image. Closing is similar to the opening operation. In closing operation, the basic premise is that the closing is opening performed in reverse. It is defined simply as a dilation follow
2 min read
Python | Morphological Operations in Image Processing (Gradient) | Set-3
In the previous articles, the Opening operation and the Closing operations were specified. In this article, another morphological operation is elaborated that is Gradient. It is used for generating the outline of the image. There are two types of gradients, internal and external gradient. The internal gradient enhances the internal boundaries of ob
2 min read
Arithmetic Operations on Images using OpenCV | Set-1 (Addition and Subtraction)
Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images. These operations can be helpful in enhancing the properties of the input images. The Image arithmetics are important for analyzing the input image properties. The operated images can be further used as an enhanced input im
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg