Python: setting two variable values ​​separated by comma in python

What is the difference between python between:

a, b = c, max(a, b)

      

and

a = c
b = max(a, b)

      

what does having two variable assignments set on the same line do?

+3


source to share


2 answers


Your two snippets do different things: try with a

, b

and c

equal 7

, 8

and 9

respectively.

The first snippet sets three variables in 9

, 8

and 9

. In other words, it is max(a, b)

evaluated before being a

assigned to a value c

. Basically, all it a, b = c, max(a, b)

does is push two values ​​onto the stack; variables a

and b

then assigned to these values ​​when discarded.



On the other hand, running the second snippet sets all three variables to 9

. This is because it is a

set to a value c

before calling the function max(a, b)

.

+6


source


They are different. The second is to do it

a, b = c, max(c, b)

      



because before b = max(a, b)

you assign c

to a

. Whereas the former uses the old value a

to calculate it.

+3


source







All Articles