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
You can use a set intersection for that :)
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With