Skip to content
Advertisement

How to assign multiple variables one line that depend on each other in python

So I know that you can assign multiple variables in one line like so:

JavaScript

But can you assign a variable based off of the value of another variable in one line?

Idea:

JavaScript

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

Advertisement

Answer

Using the the walrus operator it’s possible, if a bit ugly

JavaScript

NOTE: Assignment expressions (the walrus operator) are only available from Python 3.8 onwards

Advertisement