Suppose I have a Python list lst
. I want to convert this to a function or callable, which may be done by:
def lst_as_function(idx): return lst[idx]
or (less preferably):
lst_as_lambda_function = lambda idx: lst[idx]
However, as this seems to be a very natural operation, I wondered whether there exists a built-in (perhaps more efficient) way to achieve this.
(To be a little bit more precise: Is there a Python built-in function convert
such that I could write lst_as_function = convert(lst)
?)
Does anybody know?
Advertisement
Answer
There actually is (if I understand your question correctly):
>>> a = [10, 20, 30, 40, 50] >>> f = a.__getitem__ >>> f(2) 30