Home > database >  function returns multiple values, assignment to tuples with different number of entries?
function returns multiple values, assignment to tuples with different number of entries?

Time:07-02

A Python-function foo(p, q) calculates four values a, b, c, and returns

return a, b, c, d

In the calling function I need an assignment like

(r, s, t, u) = (p, q, foo(p, q))

or

((r, s), (t, u)) = ((p, q), foo(p, q))

How does the code look like?

CodePudding user response:

The structure of the receivers should be the same as what's being assigned and returned.

r, s, (w, x, y, z) = p, q, foo(p, q)

If you only want the last two elements of the foo(p, q) respnse you can slice it:

r, s, (w, x) = p, q, foo(p, q)[2:]

or use * in the assignment:

r, s, (*_, w, x) = p, q, foo(p, q)
  • Related