Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructing assignment order in Python

Tags:

python

Today I came across this expression:

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

...and I'm wondering what is the order of assignment.


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

What's the rule it follows? And what happens in more complex conditions like the first code snippet?

like image 740
apple apple Avatar asked Mar 08 '18 14:03

apple apple


People also ask

What are destructuring assignments in Python?

While list comprehensions are still the shiniest tool, destructuring is where the power lies. Destructuring assignments are a shorthand syntax for mapping one or more variables from the left-hand side to the right-hand side counterparts. It’s handy in unpacking values as we shall see shortly.

How to print the ordered and unordered list in Python?

my_list = [67, 2, 999, 1, 15] # this prints the unordered list print ("Unordered list: ", my_list) # sorts the list in place my_list.sort () # this prints the ordered list print ("Ordered list: ", my_list) If the list is already sorted then it will return None in the console.

What is the difference between list comprehensions and destructuring assignments?

While list comprehensions are still the shiniest tool, destructuring is where the power lies. Destructuring assignments are a shorthand syntax for mapping one or more variables from the left-hand side to the right-hand side counterparts.

How to destruct a Python dictionary and extract its properties?

myobj = types.SimpleNamespace (x=1, y=2) mydict = {"a": 1, "b": 2} with kwargs_as_modules (one=myobj, two=mydict): from one import a, b from two import x, y assert a == x, b == y You can destruct a python dictionary and extract properties by unpacking with .values () method:


1 Answers

The relevant part of the documentation on assignment statements is:

If the target list is a comma-separated list of targets, or a single target in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

(Emphasis mine: that's how the order is determined.)

like image 107
millimoose Avatar answered Sep 30 '22 15:09

millimoose