This should be an easy one: how do I apply a function to a tuple in Python?
Viz.:
Python 3.9.9 (main, Nov 16 2021, 09:34:38)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def g(a,b):
... return a+b
...
>>> tup = (3,4)
>>>
>>> g(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: g() missing 1 required positional argument: 'b'
>>> g.apply(tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'apply'
>>> apply(g,tup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'apply' is not defined
I can certainly write a version of g
that expects a tuple, or even a conversion function that does it for a general 2-arg function:
>>> def conv2(fun):
... def tuplefun(tup):
... (a,b) = tup
... return fun(a,b)
... return tuplefun
...
>>> tuple_g = conv2(g)
>>> tuple_g(tup)
7
... but this doesn't work for the general case of an arbitrary-arity function.
(ObResearch: I searched for an answer to this question for about five minutes and found a whole bunch of questions about pandas dataframes but none that appeared to answer this question. I'm sure this has an easy answer, and I apologize for not finding it, but if I'm not finding it, then probably lots of others are too... in other words, a "duplicate of question #XXXXX" would be very welcome here.)
(As an ironic-to-me side note, my most-liked question is exactly this same question about the Scala language, from back in 2010. I guess my role in life is functional-programmer-raiding-other-languages...?)