Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple assignments with a comma in python

Tags:

python

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?

like image 706
Edward Zambrano Avatar asked Jan 05 '16 20:01

Edward Zambrano


People also ask

How are multiple assignments made in Python?

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.

Does Python support multiple assignments?

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.

Does Python have comma operator?

The comma is not an operator in Python; therefore, the precedence concept doesn't work here.


1 Answers

The answer is

a = b, c ="AB"

acts like:

a = (b, c) = "AB"

This is why:

a = "AB" and b = "A" and c = "B"
like image 103
ᴀʀᴍᴀɴ Avatar answered Sep 26 '22 19:09

ᴀʀᴍᴀɴ