I tried to find an explanation of this, the Gotcha part:
b = "1984"
a = b, c = "AB"
print(a, b, c)
returns:
('AB', 'A', 'B')
I understand what happens with multiple equals:
a = b = 1
but using it together with a comma, I cannot understand the behaviour, ideas in why it works that way?
Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.
Assign Values to Multiple Variables in One Line Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left.
The comma is not an operator in Python; therefore, the precedence concept doesn't work here.
The answer is
a = b, c ="AB"
acts like:
a = (b, c) = "AB"
This is why:
a = "AB" and b = "A" and c = "B"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With