# Can we assign a reference to a variable in Python?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Concept of variable in Python is different from C/C++. In C/C++, variable is a named location in memory. Even if value of one is assigned to another, it creates a copy in another location.

int x=5;
int y=x;

For example in C++, the & operator returns address of the declared variable.

cout<x<<&x<<y<<&y;

This will print different address of x and y even though both contain same value. You can create an alias to it by storing the address in a reference variable

int x=5;
int &y=x;
y=10;
cout<<x<<y;

This shows both variables having 10. Here, y is a reference to x. Hence they can be interchangeably used.

However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function.

>>> x=5
>>> y=x
>>> id(x), id(y)
(1486402752, 1486402752)

It therefore is clear that in Python, we can not create reference to a variable.

Updated on 20-Feb-2020 08:11:01