2

Very basic question but I think I am missing some background that I would like to understand.

Let's say we have expressions:

# version 1
a = [x,y,z] = "123"

#version 2
[x,y,z] = "123"
a = [x,y,z]

I know that first version is a messy code, but I wish to understand. Always I thought that result of this code is the same. I was wrong. Type of first "a" is a string, type of second "a" is a list. The question is why in the first case the type of the most right value is propagated to the left?

pmoniq
  • 951
  • 10
  • 24

1 Answers1

5

Unlike in C, = is not an operator, and the statement

a = [x,y,z] = "123"

is not parsed as a = ([x,y,z] = "123"). It does not take the result of the [x,y,z] = "123" assignment and assign it to a.

The syntax of an assignment statement in Python is

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)

and, as stated in the documentation,

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

"123" is assigned to both a and [x,y,z], starting with a.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • But what about: [x,y,z] = a = "123" (which also prints "123")? If it was evaluated from left to right it would be ["1","2","3"], right?? – Anton vBR Jul 15 '17 at 22:54
  • 2
    @AntonvBR: No. It would assign `"123"` to `[x, y, z]`, and then it would assign `"123"` to `a`. – user2357112 Jul 15 '17 at 22:56
  • Thanks for the clarification – Anton vBR Jul 15 '17 at 22:58
  • @user2357112 do you know what is the philosophy behind this solution, why is so different then e.g. in C? – pmoniq Jul 15 '17 at 22:59
  • 1
    @pmoniq: While there are a number of arguments I can give in support of Python's assignment design (for example, it's really confusing how `a = b = 4.5` can end up [assigning `4` to `a` in C even if `a` is a double](http://ideone.com/T4UXtV), and we don't want intermediate assignments to cause weird type conversions in Python), a lot of it is just weird historical accident, and there are parts of the design I strongly disagree with. – user2357112 Jul 15 '17 at 23:10
  • Ok, with this example in C, I understand the point. – pmoniq Jul 15 '17 at 23:34