0

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

3
  • call it with a list like: polynom(1, [2, 3, 4]) Commented May 3, 2021 at 10:09
  • 1
    or change it to this: def polynom(x, *coeff_arr) ;) Commented May 3, 2021 at 10:15
  • 1
    "I obviously get the error that 2 positional arguments are needed but 4 were given when I try to run it" That is not obvious. Please show how you run it. Commented May 3, 2021 at 10:16

1 Answer 1

1

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)

)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much. I first obtained the coeff_arr using the curve_fit() function of scipy on my data and then called the function using polynom(x, coeff_arr).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.