views:

147

answers:

4

Hi, In Python if I have 2 lists say:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']

is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d)

I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function

Thanks

+7  A: 

You can use a set intersection for that :)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
WoLpH
+6  A: 
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
S.Mark
+5  A: 

If you only have unique elements, you can use the set data type and use intersection:

s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
mojbro
+1  A: 

Using sets:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']


def list_count_common(list_a, list_b):
    result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
    return result

print list_count_common(l1, l2) ## prints 2
Powertieke