removing unmatching items from 2 lists in python

list, python

Solution

You could do something like this with list comprehension:

list_intersection = [item for item in List1 if item in List2]

This will iterate over all the items in `List1` and return only the elements that are also in `List2`.

The `list_intersection` variable will now contain only element that appear in both lists ignoring the items that only appear in one of the lists.

If you don't mind duplicates being removed as part of this intersection process, you could convert both lists to sets and execute `set1.intersection( set2 )`. This will do the same thing - but remember, converting a list to a set will remove duplicates. Once you're done, you can convert the set back into a list.

l1 = [ 1, 1, 2, 3 ]
l2 = [ 2, 3, 4, 3 ]
l3 = set( l1 ).intersection( set( l2 ) )
l3 = list( l3 )

The variable `l3` will now be equal to `[2, 3]` because those are the only two element that appear in both original lists.

Problem

I need to remove all unmatching items from list1 if it does not exist in list2 ``` List1 = ['dog', 'cat', 'bird'] List2 = ['dog'] for x in List2: for y in List1: if x!=y: List1.remove(x) ``` This loop stucks after removing one item from list1. What is the correct code for this operation

Original source