Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python find number of same elements in 2 lists

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

like image 239
John Avatar asked Mar 23 '10 13:03

John


2 Answers

You can use a set intersection for that :)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
like image 164
Wolph Avatar answered Sep 18 '22 15:09

Wolph


>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
like image 36
YOU Avatar answered Sep 18 '22 15:09

YOU