jorgegarciax2
jorgegarciax2

Reputation: 67

Intersection with non unique items in Python

I have two arrays and i want the intersection of them including duplicate items:

a = [0, 0, 1, 4, 5]
b = [0, 4, 6]


set(a) & set(b)
>>> [0, 4] #Result

If i do this the result not include duplicates elements

I would like to return :

>>> [0, 0, 4]

Ideas??

Upvotes: 0

Views: 233

Answers (2)

Nishant Patel
Nishant Patel

Reputation: 1406

Set operation works for unique elements only in Python. You might want to use list comprehension for this

Result = [element for element in a if element in b]

Upvotes: 1

Pythonist
Pythonist

Reputation: 697

Assuming only a has duplicates, you can use:

[i for i in a if i in b]

Upvotes: 2

Related Questions