How can we speed up Python "in" operator?


The python operator performs very badly in a list, O(n), because it traverses the whole list. You can use something like a set or a dict(hashed data structures that have very fast lookups) to get the same result in ~O(1) time!

But this also depends on the type of data structure you're looking at. This is because while lookups in sets/dicts are fast, insertion may take more time than list. So this speedup really depends on the type.

Updated on 30-Jul-2019 22:30:22