How can we speed up Python "in" operator?

PythonProgramming

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.

raja
Published on 19-Apr-2018 16:08:39
Advertisements