Which one of these is faster? Is one "better"? Basically I'll have two sets and I want to eventually get one match from between the two lists. So really I suppose the for loop is more like:
for object in set:
if object in other_set:
return object
Like I said - I only need one match, but I'm not sure how intersection()
is handled, so I don't know if its any better. Also, if it helps, the other_set
is a list near 100,000 components and the set
is maybe a few hundred, max few thousand.
I wrote a simple utility that checks if two sets have at least one element in common. I had the same optimization problem today and your post saved my day. This is just a way to thank you for pointing this out, hope this will help other people too :)
Notice. The utility does NOT return the first element in common but rather returns true if they have at least one element in common, false otherwise. Of course it can be easily hacked to meet your goal.
Your code is fine. Item lookup
if object in other_set
for sets is quite efficient.Times:
Making them into sets in the setup and running 10000 runs instead of 100 yields
So your version is much faster whether or not it makes sense to convert them to sets.