Open In App

Variables under the hood in Python

Improve
Improve
Like Article
Like
Save
Share
Report

In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=):

Python3




# Variable named age
age = 20
print(age)
  
# Variable named id_number
id_no = 4067613
print(id_no)


Output:

20
4067613

From the above program it can be clarified that  “age is assigned a value of 20” and “id no is assigned a value of 4067613”. Now age and id_no can be used in a statement or expression, and its value will be substituted.

In python variables are dynamic i.e The type of variable is known at the run time and also a variable may be assigned a value of one type and then later re-assigned a value of a different type.

What is actually happening when you make a variable assignment in Python? 

Python is an object-oriented language. Any data item in a Python program is an object of a certain type or class like integer, float, string, etc.

From the above variable example when we are assigning value 20 to variable age the interpreter does the following:

  1. Creates an integer object
  2. Gives it the value 20
  3. Displays it to the console

Python3




# type() built in function 
# say the type of variable
age = 20
print(type(age))


Output:

<class 'int'>

Actually python variable is a symbolic name that is a reference or pointer to an object. When an object is assigned to a variable, the reference of the object can be used by its name, the data is also stored within the object itself.

Multiple object reference:

It refers to referencing an object to a previously assigned object.

Let’s have a look at this code below:

Python




# Multi object reference
age=20
new_age=age
print(age)
print(new_age)


Output:

20
20

Here, Python does not create another object. It simply creates a new symbolic name or reference, new_age which points to the same object that was previously assigned.

If we change the value of new_age for example new_age=30, then Python creates a new integer object with the value 30, and new_age becomes a reference to it.

Garbage collection:

If we change the value of the above variable age=25, then new integer object with value 25 is created and age is referenced to it. Now the integer object that has 20 in it has been orphaned or lost the reference. There is no way to access it. If there is at-least a single reference to the object then it can be alive. When the number of references to an object drops to zero python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. This is how garbage collection is done in Python.

Note: For more information, refer Garbage Collection in Python



Last Updated : 01 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads