views:

383

answers:

3

This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for.

x, y = x + 3 * y, 4 * x + 1 * y

Is this a special Python syntax?

+16  A: 
x, y = x + 3 * y, 4 * x + 1 * y

is the equivalent of:

x = x + 3 * y
y = 4 * x + 1 * y

EXCEPT that it uses the original values for x and y in both calculations - because the new values for x and y aren't assigned until both calculations are complete.

The generic form is:

x,y = a,b

where a and b are expressions the values of which get assigned to x and y respectively. You can actually assign any tuple (set of comma-separated values) to any tuple of variables of the same size - for instance,

x,y,z = a,b,c

would also work, but

w,x,y,z = a,b,c

would not because the number of values in the right-hand tuple doesn't match the number of variables in the left-hand tuple.

Amber
i think a temporary variable adds clarity. hope you don't mind
hop
I actually think that explaining it with an emphasized "EXCEPT" drives home the point clearer, so I reverted the change. Thanks anyways for the attempt at improvement, I just happen to be of a different mind on the matter. :)
Amber
Makes perfect sense. Seeing it wrapped in parentheses made it totally clear. Very easy to read it fast and miss that little detail. Thanks!
j0rd4n
+12  A: 

It's an assignment to a tuple, also called sequence unpacking. Probably it's clearer when you add parenthesis around the tuples:

(x, y) = (x + 3 * y, 4 * x + 1 * y)

The value x + 3 * y is assigned to x and the value 4 * x + 1 * y is assigned to y.

It is equivalent to this:

x_new = x + 3 * y
y_new = 4 * x + 1 * y
x = x_new
y = y_new
sth
Probably even clearer if you group the parentheses differently: `x, y = (x + 3 * y), (4 * x + 1 * y)`. The comma can be easy to miss in there.
Daniel Pryden
Ah, yes, the parentheses made it all clear -- eyes couldn't see it before [slaps forehead]...
j0rd4n
A: 

I also recently saw this referred to as "simultaneous assignment", which seems to capture the spirit of several of the answers.

Jenn D.