trynerror
trynerror

Reputation: 229

Python: array as an argument for a function

I wanted to know how to work with an array as a functional argument in Python. I will show a short example:

def polynom(x, coeff_arr):
    return coeff_arr[0]+ coeff_arr[1]+x +coeff_arr[2]*x**2

I obviously get the error that 2 positional arguments are needed but 4 were given when I try to run it, can anybody tell me how to do this accept just using (coeff_arr[i]) in the argument of the function? Cheers

Upvotes: 0

Views: 1072

Answers (1)

Christoph Burschka
Christoph Burschka

Reputation: 4689

Your question is missing the code you use to call the function, but from the error I infer that you are calling it as polynom(x, coefficient1, coefficient2, coefficient3). Instead you need to either pass the coefficients as a list:

polynom(x, [coefficient1, coefficient2, coefficient3])

Or use the unpacking operator * to define the function as follows, which will take all positional arguments after x and put them into coeff_arr as a list:

def polynom(x, *coeff_arr):

(The unpacking operator can also be used in a function call, which will do the opposite of taking a list and passing its elements as positional arguments:

polynom(x, *[coefficient1, coefficient2, coefficient3])

is equivalent to

polynom(x, coefficient1, coefficient2, coefficient3)

)

Upvotes: 1

Related Questions