Aliasing in Python

In python programming, the second name given to a piece of data is known as an alias. Aliasing happens when the value of one variable is assigned to another variable because variables are just names that store references to actual value.

Consider a following example:

first_variable = "PYTHON"
print("Value of first:", first_variable)
print("Reference of first:", id(first_variable))


second_variable = first_variable # making an alias
print("Value of second:", second_variable)
print("Reference of second:", id(second_variable))

In the example above, first_variable is created first and then string ‘PYTHON’ is assigned to it. Statement first_variable = second_variable creates an alias of first_variable because first_variable = second_variable copies reference of first_variable to second_variable.

To verify, let’s have look at the output of the above program:

Value of first_variable: PYTHON
Reference of first_variable: 2904215383152
Value of second_variable: PYTHON
Reference of second_variable: 2904215383152

From the output of the above program, it is clear that first_variable and second_variable have the same reference id in memory.

So, both variables point to the same string object ‘PYTHON’.

And in Python programming, when the value of one variable is assigned to another variable, aliasing occurs in which reference is copied rather than copying the actual value.