Write a Python program to find the union and intersection of two user given lists

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 : [9, 10, 4, 5] Input : lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69] lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26] Output : [9, 11, 26, 28]

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Method 1:
This is the simplest method where we haven’t used any built-in functions.

Python3




# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))

Output:

[9, 11, 26, 28]

Method 2:
This method includes the use of set() method.



Python3




# Python program to illustrate the intersection
# of two lists using set() method
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
print(intersection(lst1, lst2))

Output:

[9, 10, 4, 5]

Method 3:
In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set.

Python3




# Python program to illustrate the intersection
# of two lists using set() and intersection()
def Intersection(lst1, lst2):
return set(lst1).intersection(lst2)
# Driver Code
lst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
lst2 = [9, 9, 74, 21, 45, 11, 63]
print(Intersection(lst1, lst2))

Output:

{9, 11}

Method 4:
By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program.

Python3




# Python program to illustrate the intersection
# of two lists
def intersection(lst1, lst2):
# Use of hybrid method
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
return lst3
# Driver Code
lst1 = [9, 9, 74, 21, 45, 11, 63]
lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
print(intersection(lst1, lst2))

Output:

[9, 9, 11]

Method 5:
This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter().

Python3




# Python program to illustrate the intersection
# of two lists, sublists and use of filter()
def intersection(lst1, lst2):
lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
return lst3
# Driver Code
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
print(intersection(lst1, lst2))

Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2.
Output:

[[13, 32], [7, 13, 28], [1, 6]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python list-programs
python-list
Practice Tags :
python-list
Read Full Article

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 repetition only Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, 12, 26, 32, 47, 54] Maintained repetition and order Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 26, 32, 47, 48, 52, 54] Without repetition Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26] Union of three lists Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59] Output : [32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, 48, 47, 78, 20, 52, 54, 23, 25, 26, 59]

Python Program Find Union and Intersection of Two Arrays

  • Algorithm to find union and intersection of two arrays
  • Python program to find union and intersection of two arrays

Algorithm to find union and intersection of two arrays

  1. First of all, Take two lists from the user.
  2. Take thebitwise or (|)between the sets of both arrays to find union and assign it into a variableXin the form of lists.
  3. To find the intersection of between two arrays, use thebitwise and (&)between the sets of given arrays and assign it into a variableYin the form of lists.
  4. Print variableXandYwhich is our required output.

Python program to find union and intersection of two arrays

Use the following steps to write a python program to find union and intersection of two arrays:

  • Take input Two arrays from the user in the program.
  • Find the union and intersection of these arrays bitwise operators.
  • Store result in different variables.
  • Print result.
# Program to find the union and intersection of two arrays #take input two array from user firstArr=list(map(int,input('Enter elements of first list:').split())) secondArr=list(map(int,input('Enter elements of second list:').split())) # find the union and intersection of two arrays #using bitwise operators x=list(set(firstArr)|set(secondArr)) y=list(set(firstArr)&set(secondArr)) #print list print('Union of the arrays:',x) print('intersection of the arrays:',y)

After executing the program, the output will be:

Enter elements of first list: 2 5 6 Enter elements of second list: 5 7 9 6 Union of the arrays: [2, 5, 6, 7, 9] intersection of the arrays: [5, 6]

Find the union and intersection of two arrays in Python

Here, we are going to learn how to find the union and intersection of two arrays in Python programming language?
Submitted by Bipin Kumar, on October 25, 2019

Two arrays will be given by the user and we have to find the union and intersection of these arrays in the Python programming. To find the union and intersection of these arrays, we will use the bitwise or (|) and bitwise and (&) respectively between the set of the given arrays. Before going to solve this problem we will learn about the union and intersection.

Union and intersection of two arrays

A list that has the common distinct element from both arrays and if there are repetitions of the element then only one occurrence is considered, known as the union of both arrays.

A list that has common distinct elements from both arrays, is the intersection of both arrays.

Algorithm to solve this problem

  1. Initially, we will take two lists from the user which may have repeated numbers or not.
  2. We will take the bitwise or (|) between the sets of both arrays to find union and assign it into a variable A in the form of lists.
  3. To find the intersection of both arrays, we will use the bitwise and (&) between the sets of given arrays and assign it into a variable B in the form of lists.
  4. Print variable A and B which is our required output.

Let's start writing the Python program by the implementation of the above algorithm.

Code:

a=list(map(int,input('Enter elements of first list:').split())) b=list(map(int,input('Enter elements of second list:').split())) A=list(set(a)|set(b)) B=list(set(a)&set(b)) print('Union of the arrays:',A) print('intersection of the arrays:',B)

Output

Enter elements of first list: 3 4 6 4 4 6 7 41 Enter elements of second list: 78 3 5 7 -1 9 2 -5 Union of the arrays: [2, 3, 4, 5, 6, 7, 41, 9, 78, -5, -1] intersection of the arrays: [3, 7]

set() function is inbuilt in Python which is used to convert a list into another list which does not contain duplicate or repeated elements.

Python Array Programs »

Python program to find remainder of array multiplication divided by divisor
Python program to create matrix in Python

ADVERTISEMENT


Preparation


Aptitude Questions MCQs Find Output Programs

What's New

  • MongoDB MCQs
  • Java MCQs
  • C# MCQs
  • Scala MCQs
  • Blockchain MCQs
  • AutoCAD MCQs
  • PHP MCQs
  • JavaScript MCQs
  • jQuery MCQs
  • ReactJS MCQs
  • AngularJS MCQs
  • JSON MCQs
  • Ajax MCQs
  • SASS MCQs
  • HTML MCQs
  • Advanced CSS MCQs
  • CSS MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • MS Word MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • Software Engineering MCQs
  • MIS MCQs
  • Generally Accepted Accounting Principles MCQs
  • Bills of Exchange MCQs
  • Business Environment MCQs
  • Sustainable Development MCQs
  • Marginal Costing and Absorption Costing MCQs
  • Globalisation MCQs
  • Indian Economy MCQs
  • Retained Earnings MCQs
  • Depreciation MCQs
  • Partnership MCQs
  • Sole Proprietorship MCQs
  • Goods and Services Tax (GST) MCQs
  • Cooperative Society MCQs
  • Capital Market MCQs
  • Business Studies MCQs
  • Basic Accounting MCQs
  • MIS Executive Interview Questions
  • Go Language Interview Questions
ADVERTISEMENT

Top Interview Coding Problems/Challenges!

  • Run-length encoding (find/print frequency of letters in a string)
  • Sort an array of 0's, 1's and 2's in linear time complexity
  • Checking Anagrams (check whether two string is anagrams or not)
  • Relative sorting algorithm
  • Finding subarray with given sum
  • Find the level in a binary tree with given sum K
  • Check whether a Binary Tree is BST (Binary Search Tree) or not
  • 1[0]1 Pattern Count
  • Capitalize first and last letter of each word in a line
  • Print vertical sum of a binary tree
  • Print Boundary Sum of a Binary Tree
  • Reverse a single linked list
  • Greedy Strategy to solve major algorithm problems
  • Job sequencing problem
  • Root to leaf Path Sum
  • Exit Point in a Matrix
  • Find length of loop in a linked list
  • Toppers of Class
  • Print All Nodes that don't have Sibling
  • Transform to Sum Tree
  • Shortest Source to Destination Path

Comments and Discussions!



Please enable JavaScript to view the comments powered by Disqus.
ADVERTISEMENT

Python Program to Find Intersection of Two Lists

In this tutorial, we will discuss how we can get the intersection of the two lists. The intersection of two lists means we need to get all the familiar elements to both of the initial lists.

Python is known for its excellent built-in data structure. Python list is one of the famous and valuable built-in data types of Python. It can store the various data-types value in sorted order. However, there is no built-in function for lists like sets.

Python provides the many ways to perform the intersection of the lists. Let's see the following scenario.

Input :

Output:

[90, 11, 58, 31, 66, 28, 54]

Input :

Output:

[9, 11, 26, 28]

Let's see following methods to get intersection of two lists.

Method - 1: Using for loop

Output:

[90, 11, 58, 31, 66, 28, 54]

We have used for loop to get the common value from both lists and stored it in the list3 variable.

Method - 2: Convert List to Set

Output:

[66, 90, 11, 54, 58, 28, 31]

Method - 3:

We will use the built-in set's intersection() method. The intersection() is a first-class part of the set. Let's understand the following example.

Example -

Output:

{66, 90, 11, 54, 58, 28, 31}

Method - 4:

In this method, we will use the hybrid method. This is much efficient way to perform the task. Let's understand the following example.

Example -

Output:

[90, 11, 58, 31, 66, 28, 54]

Method - 5:

In this method, we will use the filter() method. The intersection is performed over sub-lists inside other lists. Let's understand the following example.

Example -

Output:

[[17, 23, 40], [10], [60]]

The filter() method takes each item of the sublist and checks if it is present in the list1. The list comprehension is executed for each sublist in the list2.

Next TopicHow to Create Requirements.txt File in Python


← prev next →


How to find the intersection and union of two lists in Python

Date: 2008-01-03 | Modified: 2008-09-09 | Tags: datastructures, python | 6Comments

My friend Bill had previously alerted me to the coolness of Python sets. However I hadn't found opportunity to use them until now. Here are three functions using sets to remove duplicate entries from a list, find the intersection of two lists, and find the union of two lists. Note, sets were introduced in Python 2.4, so Python 2.4 or later is required. Also, the items in the list must be hashable and order of the lists is not preserved.

For more information on Python sets, see the Library Reference.

""" NOTES: - requires Python 2.4 or greater - elements of the lists must be hashable - order of the original lists is not preserved """ def unique(a): """ return the list with duplicate elements removed """ return list(set(a)) def intersect(a, b): """ return the intersection of two lists """ return list(set(a) & set(b)) def union(a, b): """ return the union of two lists """ return list(set(a) | set(b)) if __name__ == "__main__": a = [0,1,2,0,1,2,3,4,5,6,7,8,9] b = [5,6,7,8,9,10,11,12,13,14] print unique(a) print intersect(a, b) print union(a, b)

Results:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [8, 9, 5, 6, 7] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Related posts

  • An example using Python's groupby and defaultdict to do the same task — posted 2014-10-09
  • python enum types — posted 2012-10-10
  • Python data object motivated by a desire for a mutable namedtuple with default values — posted 2012-08-03
  • How to sort a list of dicts in Python — posted 2010-04-02
  • Python setdefault example — posted 2010-02-09
  • How to conditionally replace items in a list — posted 2008-08-22

Comments


#1 Derek commented on 2010-02-25:

You may also want to check out this: [//stackoverflow.com/questions/642763/python-intersection-of-two-lists]


#2 Eliot commented on 2010-02-25:

Derek: Thanks. My method is simple, but it has its limitations.


#3 panta commented on 2011-04-17:

thanks for the above - very helpful. do you also know a good solution for intersection & union without eliminating the duplicates beforehand? say I have

a = [1,1,2,4,4]

b = [1,4,4,4]

I would like to get

for intersection = [1,4,4]

and for union = [1,1,2,4,4,4].

Right now, I cannot think of anything better than two nested loops.

Thanks.


#4 Jey commented on 2013-05-07:

Thank you. It was exactly what I was looking for!


#5 Dobes commented on 2014-05-28:

@panta,

How about this:

def to_multiset(x): result = set() max_rep = len(x) for elt in x: for n in xrange(max_rep): n_elt = (elt,n) if n_elt not in result: result.add(n_elt) break return result def from_multiset(x): return sorted([elt for elt,n in x]) def multi_union(a, b): aa = to_multiset(a) bb = to_multiset(b) return from_multiset(aa | bb) def multi_intersect(a, b): aa = to_multiset(a) bb = to_multiset(b) return from_multiset(aa & bb) a = [1, 1, 2, 4, 4] b = [1, 4, 4, 4] expected_intersection = [1, 4, 4] expected_union = [1, 1, 2, 4, 4, 4] print multi_union(a, b), expected_union print multi_intersect(a, b), expected_intersection

#6 Francesco SkZ Mauro commented on 2017-09-23:

nice, but set works well only for sorted list, or for list where you don't care about order of the elements.
set([1,3,5,7,9]+[2,4,6,8])={1,2,3,4,5,6,7,8,9}
set([1,2,3,7,8,9]+[3,4,5,6,7,8])={1,2,3,4,5,6,7,8,9}

disqus:3532085313

Video liên quan

Postingan terbaru

LIHAT SEMUA