2
votes

Let's say at I have a function f which has some required and optional formal parameters (and so can be called with a different number of arguments at different points). Say for a particular call to f I have a list, L, which has, in order, the arguments I want to pass to f. Is there any way to call f using L such that the ith element of L is used as the ith actual parameter passed to f?

Or more generally, having a the list L be expanded to the next arguments passed.

In matlab terms L would be a cell array so if I had a matlab function f

function val=f(a1,a2,a3, a4)
    % test to see if a4, opt arg, was passed
    % if not, default it to 0;
    if(~exist('a4','var')) 
       a4=0;
    end
    val = a1+a2+a3+a4;
end

and a matlab cell array,C (conceptually corresponds to the python list L above)

C = {1,2,3};

I could call f like:

result=f(C{:}) % so result= 6

so C{i} is passed as the ith argument.

Another call to f the input cell array might 4 items and use the same syntax to call f

or this

result = f(1,C{i,J})

so the first arg passed is 1 and the rest are the cell array elements i through j

1

1 Answers

4
votes

Put a * in front of the list name in the function call (look here for more info http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).

So, if your list was L, you would do

result = f(*L)

If you only want to use certain elements of L, say from i to j (not including j since slicing is exclusive on the right side), then first slice the list, and then do the same as above:

result = f(*L[i:j])

For your last example of inputting an argument and using other list elements as other arguments, it's similar, see below:

lst = [1, 2, 3, 4]
def f(a, b, c, d):
    return b
print(f(1, *lst[1: 4]))
#this would print 2