Paranth Paranth - 6 months ago 8
Python Question

What is the logic i should follow to print common elements in two lists

If the lists are

a= [4,6,7,4,8,9]
b= [3,4,5,2,4]


and the
output should be
[4,4]


Since 4 is repeated twice in list a and b

Answer

Turn both lists into sets and take the intersection. But your elements have repetitions, so you need to use "multisets".

>>> from collections import Counter
>>> commonctr = Counter(a) & Counter(b)  # multiset intersection
>>> common = list(commonctr.elements())  # convert back to list
>>> print(common)
[4, 4]
Comments