0

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.

2 Answers 2

4

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.

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

3 Comments

It seems odd that a method would return multiple variables. I don't remember seeing this in any other language (C#, VB, Java, PHP). Is this a Python thing?
Other languages have to do a bit more work to do the same thing (return a struct, or a class instance, or a hashmap...)
This takes the place of something that (some) other languages have that python doesn't (or not trivially): you can't change the value of a variable passed to a function.
1

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.

3 Comments

Any idea where print(res) is being defined? I am thinking the code says res but they meant to say residuals?
I guess so, it's hard for me to tell without even knowing which book it is :-)
Sorry, it's Building Machine Learning Systems with Python. I am just trying to understand the code therein. Thanks, anyway.

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.