user1477388
user1477388

Reputation: 21440

Python Multiple Variable Declaration

I am reading a book, in which they write:

fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full=True)

It seems sp.polyfit method assigns values to each of these variables in some sort of order.

For instance:

>>> print("Model parameters: %s" % fp1)
Model parameters: [ 2.59619213 989.02487106]
>>> print(res)
[ 3.17389767e+08]

(I don't know where res is being defined... but...) Is this Python's way of creating an object?

In other languages, you might do something like this:

Foo myFooObject = bar.GenerateFoo();
myFooObject.foo();
myFooObject.bar();

The general syntax of python in this way is confusing to me. Thanks for helping me to understand.

Upvotes: 0

Views: 213

Answers (2)

RemcoGerlich
RemcoGerlich

Reputation: 31270

It's tuple unpacking.

Say you have some tuple:

t = (1, 2, 3)

then you can use that to set three variables with:

x, y, z = t  # x becomes 1, y 2, y 3

Your function sp.polyfit simply returns a tuple.

Actually it works with any iterable, not just tuples, but doing it with tuples is by far the most common way. Also, the number of elements in the iterables has to be exactly equal to the number of variables.

Upvotes: 1

Andrew Jaffe
Andrew Jaffe

Reputation: 27107

This has nothing to do with object creation -- it's an example of tuple (or more generally sequence) unpacking in python.

A tuple is a fixed sequence of items, and you can assign one set to another via a command like

a, b, c = 1, 'two', 3.0

which is the same as

a = 1
b = 'two'
c = 3.0

(Note that you can use this syntax to swap items: a, b = b,a.)

So what is happening in your example is that scipy.poylfit has a line like

return fp, resides, rank, eval, rcondnum

and you are assigning your variables to these.

Upvotes: 4

Related Questions