Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

a, b, c = 1, 2, 3

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

Idea:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading