Im sure this was asked before, but when searching for it i only found questions like “reference last object in a list”
However, i am looking for something to make this example code not redundant – in this example i have to use two very long variables:
JavaScript
x
3
1
if response.json()["items"][0]["id"]:
2
print(response.json()["items"][0]["id"])
3
I know that powershell has $_., and im wondering if Python has something similar, so that i do not have to reference the same variable twice (for example if it is not just a small x, but a longer name like an object out of a dictionary etc.)
Advertisement
Answer
Check out the first example here: https://docs.python.org/3/whatsnew/3.8.html
You can use the walrus operator
(python 3.8) which does exactly what you want:
JavaScript
1
3
1
if (x := <long expression>):
2
print(x)
3