How to assign multiple variables one line that depend on each other in python
Question:
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
Answers:
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
This only works in 3.8+ and it gets really gross. The "Walrus Operator" lets you make assignments in an expression.
c = (a := 1 ) + (b := 2)
To understand what’s going on, you can see the difference between the "walrus" and the regular assignment in the interactive interpreter:
>>> x = 2
Returns nothing. But similarly:
>>> (x := 2)
2
Returns the 2 that was also assigned to x. So it can be used in an expression while also doing the assignment.
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
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
This only works in 3.8+ and it gets really gross. The "Walrus Operator" lets you make assignments in an expression.
c = (a := 1 ) + (b := 2)
To understand what’s going on, you can see the difference between the "walrus" and the regular assignment in the interactive interpreter:
>>> x = 2
Returns nothing. But similarly:
>>> (x := 2)
2
Returns the 2 that was also assigned to x. So it can be used in an expression while also doing the assignment.