Paranth Paranth - 2 years ago 59
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

Since 4 is repeated twice in list a and b

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download