Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign and print at the same time in Python

Tags:

python

In Python, is there a way to assign a result to a variable and immediately print it? In other words, I am looking for a one-line equivalent to

a = something()
print(a)

(just once, not every assignment should be automatically printed).

There are REPLs, e.g. for Scala, where this happens automatically:

scala> val count = 1
count: Int = 1
like image 740
Socci Avatar asked Jul 12 '26 15:07

Socci


1 Answers

As of Python 3.8, the answer to this has changed.

Now, you can assign a value to a variable and return that same value using "assignment expressions" (colloquially called "the Walrus operator").

So, this is valid Python:

print("Hello, {}".format((w := "world"))

Which will print "Hello, world" and assign the string "world" to the variable "w" all in one line.

like image 91
John O'Brien Avatar answered Jul 14 '26 04:07

John O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!