Is there any faster way to calculate this value in Python:
len([x for x in my_list if x in other_list])
I tried to use sets, since the lists' elements are unique, but I noticed no difference.
len(set(my_list).intersection(set(other_list)))
I'm working with big lists, so even the slightest improvement counts. Thanks
I think a generator expression like so would be fast
sum(1 for i in my_list if i in other_list)
Otherwise a set
intersection is about as fast as it will get
len(set(my_list).intersection(other_list))
Simple way is to find the least length'd list... than use that with set.intersection
..., eg:
a = range(100)
b = range(50)
fst, snd = (a, b) if len(a) < len(b) else (b, a)
len(set(fst).intersection(snd))
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