Destroying assignment order in Python

Today I came across this expression:

(x,_),(y,_) = load_data() 

... and I wonder what order of appointment.


For example, x,x,x = 1,2,3 set x to 3 from my test, does it really set x to 1, 2 than 3?

Which rule does this follow? And what happens in more complex conditions, such as the first piece of code?

+5
source share
3 answers

The relevant part of the documentation for assignment operators :

If the target list is a list of goals, separated by commas, or one goal in square brackets: the object must be iterable with the same number of elements as in the target list, and the goals are assigned, from left to right , to the corresponding goals.

(Emphasize mine: how the order is determined.)

+4
source

It will load a pair of tuples that load_data () returns into the x, y, and _ variables that you define. This, in turn, assigns the first member of each tuple to the x and y values ​​and the last value of the _ variable (which gets the second value after the second call).

Example:

 def load_data(): return (1,2), (3,4) (x, _), (y, _) = load_data() print(x, y, _) 

Outputs

1 3 4

+1
source

This is a really interesting question, although I must say first that you probably should not assign the same variable more than once per line.

In the first example, load_data() returns two tuples. It is assigned (x, _) first. Underline is an agreement to unpack values ​​that you do not need. It will be overwritten when the second tuple is unpacked.

0
source

Source: https://habr.com/ru/post/1275787/


All Articles