Reputation: 31
x=10, y=20
This is really short code, but when I execute this code in python, "can't assign to literal" error appears. Of course I know that this can't be executed in pyhon just intuitively, and it's out of question. This code should be changed to
x,y=10,20
or
x=10
y=20
like this. but I can't explain WHY the first code is error logically. please help me!
Upvotes: 3
Views: 239
Reputation: 2391
What python does with this:
A, B = C, D
It assigns the first value to the first variable, and the second value to the second variable:
A = C
B = D
This works because python internally makes "tuples" with your values delimited by a comma:
(A, B) = (C, D)
When you do
A = C, B = D
Python believes that you are doing:
A = (C, B) = D
Or:
(C, B) = D # Which is C = D[0] and B = D[1]
A = (C, B)
But C
in you case is a number, not a variable, so:
x = 10, y = 20
Is:
x = (10, y) = 20
Or:
(10, y) = 20
x = (10, y)
Which is not possible. You can't assign something to a number (10
). Doing 10 = 'something'
will give you SyntaxError: can't assign to literal
.
To make simpler, just execute in your python console:
10 = 1
And you will have the same error.
Upvotes: 0
Reputation: 249123
Your error is that you think x=10, y=20
means x=10; y=20
when in fact it means x=(10, y)=20
. This is because the comma creates a tuple, and you can't assign to a tuple which contains a literal (in this case 10
).
Upvotes: 6