Possible Duplicate:
Common elements comparison between 2 lists
I have two Lists:
[Apples, Bananas, Pears]
[Kiwis, Bananas, Apples]
I would like to get only the elements that both lists share. There have to be some built-in functions in python for that.
Result:
[Apples, Bananas]
Original Answer:
In response to the comment question about preserving order:
That list comprehension is just a shorthand version of
With this expanded version, it’s a little easier to see what is going on. The output list is exactly
list1with the elements that are inlist2removed. So it will preserve the order oflist1. For example, iflist1 = [1,2,3]andlist2 = [3,2,5], the output of the list comprehension will be[2,3]. If the position of the lists was reversed like thisThen the order of
list2would 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:So for your example, this happens:
But if the lists are flipped, then the output is reversed:
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.)