Suppose I have a Python list lst
. I want to convert this to a function or callable, which may be done by:
JavaScript
x
3
1
def lst_as_function(idx):
2
return lst[idx]
3
or (less preferably):
JavaScript
1
2
1
lst_as_lambda_function = lambda idx: lst[idx]
2
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):
JavaScript
1
5
1
>>> a = [10, 20, 30, 40, 50]
2
>>> f = a.__getitem__
3
>>> f(2)
4
30
5