How to Find the Intersection of Two Lists in Python


In this example, we will learn how to get two lists and find their intersection.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def userList():
    n = int(input("Please input the number of elements: "))
    a = []
    for i in range(n):
        j = int(input("Please input the element: "))
        a.append(j)
    return a

listA = userList()
listB = userList()
listC = list(set(listA).intersection(set(listB)))
print(listC)

Output:

Please input the number of elements: 6
Please input the element: 1
Please input the element: 2
Please input the element: 3
Please input the element: 4
Please input the element: 5
Please input the element: 6
Please input the number of elements: 5
Please input the element: 4
Please input the element: 5
Please input the element: 6
Please input the element: 7
Please input the element: 8
[4, 5, 6]

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement