Reference last object that was called?

Tags:



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:

if response.json()["items"][0]["id"]:
   print(response.json()["items"][0]["id"])

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.)

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:

if (x := <long expression>):
    print(x)


Source: stackoverflow