Original Answer:
[x for x in list1 if x in list2]
In response to the comment question about preserving order:
That list comprehension is just a shorthand version of
intersection = []
for x in list1:
if x in list2: #Note that using 'in' involves looping over list2
intersection.append(x)
With this expanded version, it's a little easier to see what is going on. The output list is exactly list1
with the elements that are in list2
removed. So it will preserve the order of list1
. For example, if list1 = [1,2,3]
and list2 = [3,2,5]
, the output of the list comprehension will be [2,3]
. If the position of the lists was reversed like this
[x for x in list2 if x in list1]
Then the order of list2
would be preserved in the output, giving us [3,2]
.
Also, in a possibly undesirable side effect, this means that this method will contain duplicate elements of list1
. For example:
>>> [x for x in [1,2,3,3,3] if x in [2,3]]
[2, 3, 3, 3]
So for your example, this happens:
>>> [fruit for fruit in ["Apples", "Bananas", "Pears"] if fruit in ["Kiwis", "Bananas", "Apples"]]
['Apples', 'Bananas']
But if the lists are flipped, then the output is reversed:
>>> [fruit for fruit in ["Kiwis", "Bananas", "Apples"] if fruit in ["Apples", "Bananas", "Pears"]]
['Bananas', 'Apples']
So, in general, the sets solution is better because it is more efficient and because often you won't want the duplicate elements. However, if you want to preserve order, this is the way to go. (If you want to preserve order and not have duplicates, you can just use this method and then strip out the duplicates, depending on whether you want the earlier duplicate or a later one to remain.)