In Python, find the number of identical 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 case it will be 2 (c and d)

I know that I can just execute a nested loop, but there is no built-in function, e.g. in php with array_intersect function

thanks

+5
source share
4 answers

You can use the intersection set for this :)

 l1 = ['a', 'b', 'c', 'd'] l2 = ['c', 'd', 'e'] set(l1).intersection(l2) set(['c', 'd']) 
+10
source
 >>> l1 = ['a', 'b', 'c', 'd'] >>> l2 = ['c', 'd', 'e'] >>> set(l1) & set(l2) set(['c', 'd']) 
+6
source

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

 s1, s2 = set(l1), set(l2) num = len(s1.intersection(s2)) 
+5
source

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 
+1
source

Source: https://habr.com/ru/post/1304873/


All Articles