Search code examples
pythonmicro-optimization

Fast Way of Indexing Operator in Python (lambda i: l[i])


Given an indexable data structure such as a list l, how can we get the fastest function that is equivalent to lambda i: l[i]? The problem of the lambda function is that it is Python and slows things down. There are some built-in operators in the operator module, but it appears that none of them can be used in this situation.


Solution

  • l.__getitem__ is more than twice as fast, and since that's the object's own method, I doubt you can beat it.

    >>> timeit('f(i)', 'l=[1,2,3]; i=1; f=lambda i:l[i]', number=10**8)
    17.013631199999963
    >>> timeit('f(i)', 'l=[1,2,3]; i=1; f=l.__getitem__', number=10**8)
    7.722098399999936