0

In Python, I am studying a textbook example of optimization with Lagrange multipliers. The sample source code works correctly in finding out the mathematical minimums; however, I don't understand the system behaviour of statement [x, y, λ] = xyλ in the below function:

def DL(xyλ):
    [x, y, λ] = xyλ # <-- What does this statement do?
    return np.array([
        dfdx(x, y) - λ * dgdx(x, y),
        dfdy(x, y) - λ * dgdy(x, y),
        - g(x, y)
    ])

I thought it didn't make sense to assign one single variable to an array of multiple elements. So, I am also wondering why the sample program doesn't break on that line.

James
  • 1,373
  • 3
  • 13
  • 27
  • 2
    Typically it would be written as `x, y, λ = xyλ`; It's called `unpacking`. As long as `xyλ` has 3 elements, each of those is assigned to the three variables. i.e. `x = xyλ[0]`, etc. In `optimize.root(DL, [x0, y0, l0])` the initial guess is a list of 3 values. That determines the size of array that `root` passes to `DL`. – hpaulj Apr 12 '22 at 19:23
  • This isn't "assigning to an array", this is actually "iterable unpacking". Both `()` and `[]` can be used to *group* the unpacking target, but they are equivalent. E.g. you could do something liek `(x, (y, z)) = [1, (2, 3)]` or `[x, [y, z]] = [1, (2, 3)]` or `[x, (y, z)] = [1, (2, 3)]` and they are all equivalent – juanpa.arrivillaga Apr 12 '22 at 19:32
  • See a linked duplicate for an in-depth exploration of these constructs – juanpa.arrivillaga Apr 12 '22 at 19:33

0 Answers0