0

pt1 and pt2 are two tuple made up of ints.

pairs = zip(pt1, pt2)  
sum_sq_diffs = sum((a - b)**2 for a, b in pairs)
return (sum_sq_diffs) 

My question concerns the second line. What are a and b? If you print them by doing:

 print list((a,b) for a, b in pairs))

you get [(pt1x,pt2x), (pt1y, pt2y)]

If I take two tuples and subtract them, you get an error. So how come sum_sq_diffs = sum((a - b)**2 for a, b in pairs) doesn't result in an error? It seems a is a tuple and b is a tuple.

2 Answers 2

2

You understand that pairs is a list of tuples.

Now, the second line is a list comprehension which is the equivalent of

sum_sq_diffs = 0
for a, b in pairs:
    sum_sq_diffs += (a - b)**2 

Now, while iterating through the individual elements, python would do a "tuple unpacking" for you , and extracts the (x, y) to local variables a and b respectively.

You can read more on tuple unpacking here

This is called, appropriately enough, tuple unpacking. Tuple unpacking requires that the list of variables on the left has the same number of elements as the length of the tuple. Note that multiple assignment is really just a combination of tuple packing and tuple unpacking!

Here is a quick demo which should demonstrate this:

>>> pt1 = [1, 2, 3]
>>> pt2 = [4, 5, 6]
>>> pairs = zip(pt1, pt2)  
>>> pairs
[(1, 4), (2, 5), (3, 6)]
>>> sum_sq_diffs = sum((a - b)**2 for a, b in pairs)
>>> sum_sq_diffs
27
>>> sum_sq_diffs_2 = 0
>>> for a, b in pairs:
...     print a, b
...     sum_sq_diffs_2 += (a - b)**2
... 
1 4
2 5
3 6
>>> sum_sq_diffs_2
27
>>> 
Sign up to request clarification or add additional context in comments.

Comments

0

pairs should be a list of tuples.

a, b should unpack those tuples, one at a time. So they should be scalars.

There is much to like about list comprehensions and generator expressions. One thing I don't like about them, is you tend to end up rewriting them as loops when you have a question about how they are behaving.

But I do suggest rewriting your comprehension as a loop, and inserting a print(a,b) or print a, b. It may help.

1 Comment

a, b can be about anything, not only scalars. They are what you get when unpacking pairs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.