So I know that you can assign multiple variables in one line like so:
a, b, c = 1, 2, 3
But can you assign a variable based off of the value of another variable in one line?
Idea:
a, b, c = 1, 2, a+b
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
a, b = 1, 2; c = a+b
Advertisement
Answer
Using the the walrus operator it’s possible, if a bit ugly
c = (a := 1) + (b := 2)
NOTE: Assignment expressions (the walrus operator) are only available from Python 3.8 onwards