Reggie's Linear Regression enquiry re. tuple syntax

Hi guys,
Just looking for some clarification regarding “Reggie’s Linear Regression” Off-Platform Project found here:
https://www.codecademy.com/courses/learn-python-3/informationals/python3-reggies-linear-regression

Under the calculate_error function, I don’t understand the syntax:

def calculate_error(m, b, point):
    x_point, y_point = point
  • When I printed the type, I realised it was a tuple, but why is it not enclosed in parentheses ()?
  • I also thought assignment is usually performed left to right so does this line assign both x_point and y_point to the tuple point?

In an attempt to understand it better, I inverted the line i.e.

def calculate_error(m, b, point):
   point = x_point, y_point

but then the following testing of the function no longer worked correctly.

To get around this I rewrote it as follows:

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

but I do not view this as good practice, more of a hack per say.

In short, could someone please clarify the differences:

  • why/how is it a tuple if not enclosed in ()?
  • why does the line not work if inverted and what is the difference?

Please excuse my formatting, first post. I’ll get the hang of it!

Many thanks.

1 Like

Hi!

Welcome to the forums :slight_smile:

I think the topic you might want to look at in documentation or stack overflow is called unpacking.

Here when you write x_point, y_point = point, the values of point are unpacked into new variables. You can’t invert because x_point and y_point are not yet declared. It’s not too hacky to write x_point = point[0], y_point = point[1] just a little less efficient in this case.

One element tuples have a trailing comma by convention. Otherwise, if no parenthesis are present, it is not a tuple.

It’s more clear if you experiment in the terminal, example:

>>> val1 = 1
>>> val2 = 2
>>> tuple = val1, val2
>>> tuple
(1, 2)
>>> list = [1,2]
>>> listVal1,listVal2 = list
>>> listVal1
1
>>> testVal1,testVal2 = tuple
>>> testVal1
1
>>> type(testVal1)
<class 'int'>
>>> tupleTest = (testVal1)
>>> tupleTest
1
>>> tupleTest = (1,)
>>> tupleTest
(1,)
>>> type(tupleTest)
<class 'tuple'>
>>> testVal1,testVal2 = tuple
>>> testVal1
1
>>> type(testVal1)
<class 'int'>
>>> tupleTest = (testVal1)
>>> tupleTest
1
>>> type(tupleTest)
<class 'int'>
>>> tupleTest = (1,)
>>> tupleTest
(1,)
>>> type(tupleTest)
<class 'tuple'>
2 Likes

Hi, thanks for replying so quickly! Your explanation was excellent, especially with the terminal examples. As you suggested, I also looked up “Unpacking” for further clarfication and it’s all much clearer now.

Thanks again, now I can progress in the knowledge that you’ve helped to plug what felt like a significant knowledge gap

Cheers!

1 Like