开发者

New to Python Trying to understand Syntax

开发者 https://www.devze.com 2023-03-31 00:56 出处:网络
I am new to Python and I am trying to unders开发者_JAVA百科tand this syntax: a, b = b, a + b We could rewrite this to: (a, b) = (b, a + b)

I am new to Python and I am trying to unders开发者_JAVA百科tand this syntax:

a, b = b, a + b


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.


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.


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.


a is given the value of b and b is given the value of a+b

A more technical explanation can be found here


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消