133 words — categories: python
You can pack and unpack functions arguments in Python.
If you have a function take takes in \(n\) arguments, you can’t just pass it a list of said arguments. Let’s say we have a linear function that takes in an array of \(x\)-values, a slope and intercept.
import numpy as np x_array = np.linspace(1, 10, 10) def linear(x, m, b): return x * m + b args = [2, 4]
# the operation below leads to # TypeError: linear() missing 1 required positional argument: 'b' linear(x_array, args)
Python takes in the
args list as the first positional arguments. We can use the unpacking convention instead to break up
args into its constituents.
## array([ 6., 8., 10., 12., 14., 16., 18., 20., 22., 24.])