Why different results are obtained in 2 cases?

Example 1:

A = 1 B = 2 C = 3 D = 4 E = 5 F = 6 A,B,C,D = E,F,A,B print A,B,C,D,E,F 

Result 1:

5 6 1 2 5 6

Example 2:

 A = 1 B = 2 C = 3 D = 4 E = 5 F = 6 A = E B = F C = A D = B print A,B,C,D,E,F 

Result 2:

5 6 5 6 5 6

In what order, in the first example, the variables are assigned?

  • In this order, everything is correct: C = A; D = B; A = E; B = F. But why? - Denis Leonov
  • uh ... what's wrong in case 2? absolutely logical behavior. - pavel
  • Yes, it's just that the operation A, B, C, D = E, F, A, B is apparently performed by the interpreter in its unknown order. Strange - Denis Leonov
  • one
    @Denis, why? Consistently from the end. Another question is whether this behavior is standardized between interpreter versions or not. - 0andriy

1 answer 1

E,F,A,B gives a tuple (5,6,1,2) , which has no relation to the original variables and is in no way connected with them.

 foo = E,F,A,B print(foo) # => (5, 6, 1, 2) E = -777 print(foo) # всё ещё => (5, 6, 1, 2) 

The syntax A,B,C,D = is unpacking (in this case a tuple) - sequentially assigns variables from a list, tuple, or any other iterated object (you can put = range(4) , for example) after the equal sign. And the tuple, which stands on the right, no longer has anything to do with the original variables. That is, it turns out something like:

 A,B,C,D = (5,6,1,2) 

In the second case, the code is simply executed sequentially as it is and changes the variables, I hope it does not need explanations)

More examples:

 a, b, c = [1, 2, 3] # a = 1, b = 2, c = 3 a, b, c = range(3) # a = 0, b = 1, c = 2 a, b, *l, c = range(5) # a = 0, b = 1, l = [2, 3], c = 4 

An example with its generator:

 def gen(): yield int(input('Первое число: ')) yield int(input('Второе число: ')) a, b = gen() print(a, b) 

Will give:

 Первое число: 3 Второе число: 4 3 4