python syntax comma between variables before declaration

Solutions on MaxInterview for python syntax comma between variables before declaration by the best coders in the world

showing results for - "python syntax comma between variables before declaration"
Alexander
05 Nov 2020
1What you describe is tuple assignment:
2
3a, b = 0, 1
4is equivalent to a = 0 and b = 1.
5
6It can however have interesting effects if you for instance want to swap values. Like:
7
8a,b = b,a
9will first construct a tuple (b,a) and then untuple it and assign it to a and b. This is thus not equivalent to:
10
11#not equal to
12a = b
13b = a
14but to (using a temporary):
15
16t = a
17a = b
18b = t
19In general if you have a comma-separated list of variables left of the assignment operator and an expression that generates a tuple, the tuple is unpacked and stored in the values. So:
20
21t = (1,'a',None)
22a,b,c = t
23will assign 1 to a, 'a' to b and None to c. Note that this is not syntactical sugar: the compiler does not look whether the number of variables on the left is the same as the length of the tuple on the right, so you can return tuples from functions, etc. and unpack them in separate variables.
similar questions