Reggie Linear Regression - defining variables from a tuple

Hello everyone! I have been going through the python 3 lessons in order and just wanted to check my understanding for a part of the project. I have been having issues with defining x_point and y_point for this portion of the project:

Reggie wants to try a bunch of different m values and b values and see which line produces the least error.
To calculate error between a point and a line, he wants a function called calculate_error() , which will take in m , b , and an [x, y] point called point and return the distance between the line and the point.

To find the distance:

  1. Get the x-value from the point and store it in a variable called x_point
  2. Get the y-value from the point and store it in a variable called y_point
    ā€¦

My thought process when trying to solve this task was as follows:
Originally, due to the instructions saying "an [x, y] point called point" I thought I was dealing with a list . However, looking at the input later in the project, I realised that actually you will be dealing with a tuple.

Regardless I attempted to write codes like:

def calculate_error(m,b,point):
    point[0] = x_point
    point[1] = y_point

thinking that if your input was for example calculate_error (1, 1, (2, 3)), the function would then

  1. extract element with index 0 from the tuple and set it as the x_point
  2. extract element with index 1 from the tuple and set it as the y_point

However I got a syntax error.

After much struggling, I opened the provided solution which showed this:

def calculate_error(m,b,point):
    x_point, y_point = point
    return abs(get_y(m, b, x_point) - y_point) 

So my main questions are:

  1. from the proposed solution, is the reason why x_point, y_point = point works because this is the way you unpack data from an input that is a tuple?

  2. why is my initial thought process wrong? - i.e.

point[0] = x_point
point[1] = y_point
  1. if the input was a list instead, would x_point, y_point = point still be correct? - i.e. is unpacking a tuple the same as unpacking a list?
1 Like

1, 3: yes, exactly
2: You have the assignment statement reversed. You want
variable = value
ā€¦ whereas what you have is:
value = variable

3 Likes