Intersection of two lists

A code to output the intersecting element from two lists using Python programming.

Welcome to the code! Here’s a simple code to get more familiar with lists in python programming.

The function intersect(l1,l2) that takes two sorted lists as arguments and returns the list of all elements common to both l1 and l2 in the same order that they appear in the two lists. If the same element occurs more than once in both lists, it should appear in the output exactly once.


Example;
intersect([2,2,4],[1,2,2,3,4]) should return [2, 4]
intersect([1,2,3],[4,5,6]) should return [].

Note: Loved the post? You too can publish your article on “Python for fun” which will be loved by millions. Contribute an article!

							
							
					def intersect(l1,l2):
    l = []
    lit = []
    for x in l1:
        for y in l2:
            if x==y:
                l = l+[x]
    li = set(l)
    lit = list(li)
    return(lit)

a = input("Enter the list of integers for the first list:") #input for the elements of first list
list1 = list(map(int, a.split()))
b = input("Enter the list of integers for the second list:") #input for the elements of second list
list2 = list(map(int, b.split()))

print(intersect(list1,list2))				
			
Share on facebook
Share on whatsapp
Share on pinterest
0 0 votes
Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments