So I know that you can assign multiple variables in one line like so:
JavaScript
x
2
1
a, b, c = 1, 2, 3
2
But can you assign a variable based off of the value of another variable in one line?
Idea:
JavaScript
1
2
1
a, b, c = 1, 2, a+b
2
I know that the idea code doesn’t work but is there some way to replicate this in one line even if longer or weirder?
NOTE:
Using ;
like below doesn’t count
JavaScript
1
2
1
a, b = 1, 2; c = a+b
2
Advertisement
Answer
Using the the walrus operator it’s possible, if a bit ugly
JavaScript
1
2
1
c = (a := 1) + (b := 2)
2
NOTE: Assignment expressions (the walrus operator) are only available from Python 3.8 onwards