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?
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?
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.
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
I also recently saw this referred to as "simultaneous assignment", which seems to capture the spirit of several of the answers.