Reputation: 22408
I am new to Python and I am trying to understand this syntax:
a, b = b, a + b
Upvotes: 1
Views: 192
Reputation: 586
it does two initializations in one line of code:
1. a = b
2. b = a + b
it's a alternative to use it as a swap()
function in python by the way.
Upvotes: 0
Reputation: 82078
Python has the ability to transfer multiple values at once. That means "set a to b, and b to the sum of a and b".
There is a more comprehensive explanation here.
Upvotes: 1
Reputation:
It is an assignment with a tuple-decomposition (or sequence unpacking) and might also be called a multiple assignment statement.
The tuple on the RIGHT is evaluated and then the result is assigned slot-for-slot to the variables on the LEFT. (The left side is not really a tuple even though the syntax makes it look like one.)
So,
a = 1
b = 2
a, b = b, a + b
// a, b = 2, 1 + 2
// a, b = 2, 3
// a = 2
// b = 3
Happy coding.
Upvotes: 0
Reputation: 42050
a
is given the value of b
and b is given the value of a+b
A more technical explanation can be found here
Upvotes: 1
Reputation: 46463
This is called sequence unpacking. The right-hand side is packed into a tuple (because of the comma). Python packs then evaluates the right side, then unpacks those values into the left hand side.
See Tuples and Sequences.
Upvotes: 1
Reputation: 1579
This is syntactic sugar for a python feature called 'unpacking'. It effectively means this:
(a, b) = (b, a + b) # This is also valid syntax
The tuple (b, a + b)
is created, locking in the values. Then, the values are piece-wise assigned to the identifiers in the tuple (a, b). Since the values are locked in before assignment starts, each takes on the expected value. This idea is derived from pattern matching in Haskell.
Upvotes: 1
Reputation: 2358
We could rewrite this to: (a, b) = (b, a + b)
Considering that a = 3
and b = 6
The operation (b, a + b)
returns a tupple (6, 9)
and assigns these values to the listed variables (a, b)
and assign (a = 6, b = 9)
.
So the final values are a = 6
and b = 9
.
Upvotes: 2