5

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

John
  • 21,047
  • 43
  • 114
  • 155
  • Duplicate: http://stackoverflow.com/questions/2424700/how-to-get-a-list-with-elements-that-are-contained-in-two-other-lists – S.Lott Mar 23 '10 at 13:39

4 Answers4

10

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
  • 78,177
  • 11
  • 137
  • 148
6
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
YOU
  • 120,166
  • 34
  • 186
  • 219
5

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,509
  • 13
  • 13
1

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
  • 2,368
  • 1
  • 14
  • 21