DEV Community

suvhotta
suvhotta

Posted on

2

Python - Object and Variable Difference

Let's quickly resolve confusion surrounding an Object and a Variable :

Let's say you've a list as -

fruits = ['apple','orange','grape']
Enter fullscreen mode Exit fullscreen mode

When such a list is created, the fruits is a variable holding the location of memory where the list exists.

The location can be checked with the help of the following function:

id(fruits)
Enter fullscreen mode Exit fullscreen mode

Now when you try to update the list as:

fruits = ['mango','banana','Tomato']
Enter fullscreen mode Exit fullscreen mode

(It's no typo, Tomato is actually a fruit)

You think that you've updated the earlier existing list with new values, but instead you've have actually created a new python object altogether and it's memory location is fed to the variable fruits.

This can be verified by checking -

id(fruits)
Enter fullscreen mode Exit fullscreen mode

Clearly there would be stark contrast between the memory value obtained previously and the latest one.

If no other variable is now referring to the older list, then python's garbage collector will auto-delete it from memory.

Now if you really want to update the list with fresh values, then use the following code instead :

fruits.clear()  #It clears all elements from the existing list
fruits.extend(['mango','banana','Tomato']) #populates list with new elements
Enter fullscreen mode Exit fullscreen mode

Hope this was helpful for you!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay