6

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?

4
  • 2
    expressions are evaluated from left to right. to last one wins, yes. Commented Mar 8, 2018 at 14:48
  • also, the type of 1,2,3 is a tuple. So it has a defined order. Commented Mar 8, 2018 at 14:49
  • 2
    You can find out what a statement does by entering it into the Python console. The rules are defined in the reference manual: docs.python.org/3.6/reference/simple_stmts.html - it maps tuple items in the left hand side to tuple items in the right hand side, 1:1, recursively. (When not using the star operator.) In general, if an assignment statement is ambiguous, I'd recommend just writing out multiple assignments explicitly. Commented Mar 8, 2018 at 14:52
  • 3
    import dis; dis.dis('(x,_),(y,_) = load_data()') This makes the order very clear Commented Mar 8, 2018 at 14:59

3 Answers 3

5

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

It will load the couple of tuples that load_data() returns into variables x, y and _ which you define. This in turn will assign the first member of each tuple to x and y and the last value to the _ variable (which gets overridden the second time it's called).

Example:

def load_data():
    return (1,2), (3,4)

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

print(x, y, _)

Outputs

1 3 4

Comments

0

This is a really interesting question, though I should say first that you probably shouldn't assign the same variable more than once per line.

The first example expects load_data() to return two tuples. It will assign (x, _) to the first one. The underscore is a convention for unpacking values you don't care about. It will be overwritten when the second tuple is unpacked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.