Intersection of two lists, keeping duplicates in the first list

What do you mean you don’t want to use loops? You’re going to have to iterate over it one way or another. Just take in each item individually and check if it’s in array2 as you go:

items = set(array2)
found = [i for i in array1 if i in items]

Furthermore, depending on how you are going to use the result, consider having a generator:

found = (i for i in array1 if i in array2)

so that you won’t have to have the whole thing in memory all at once.

Leave a Comment