Python Variables, Objects, and References

Spread the love
Contents:
  • Introdution
  • Variables, Objects, and References in Python
Introduction

During problem solving in Python, we need to store data of different types and we perform different operations on them. In Python, data takes the form of objects—either built-in objects that Python provides, such as strings and lists, or add-on objects we create with Python classes. So, when we need to store the data, we have to write instruction for computer in such a way that data could be stored and whenever required we can fetch the data from memory. That’s where the role of variable comes in. 

Variables, Objects, and References in Python

In Python, a variable is just a name created by you when you first assign it a data. Python variable never has any data type information or any constraints associated with it. The concept of data type lives with objects, not names. It means, variable itself is not going to tell you what kind of data it is going to store or how much memory space is required to store the data in memory like other languages like C, C++, or Java.  It is the data that decides the data type and storage requirement in Python. So, variables in Python programming language are generic. They can refer to any type of data. When a variable appears in an expression, it is immediately replaced with the object that it currently refers to, whatever that may be. In sum, variables are created when assigned, can reference any type of object, must be assigned before they are referenced and can’t be declared before assignment.
Example:  a = 3
Here a is a variable that is just a name which is referring to a number object whose value is 3. Conceptually, Python will perform three distinct steps to carry out the request. These steps reflect the operation of all assignments in the Python language:

  1. Create an object to represent the value 3.
  2. Create the variable a, if it does not yet exist.
  3. Link the variable a to the new object 3.

Here, variables and objects are stored in different parts of memory and are associated by links (the link is shown as a pointer in the figure). Variables always link to objects and never to other variables. These links from variables to objects are called references in Python—a kind of association, implemented as an object’s address in memory. Readers with a background in C may find Python references similar to C pointers (i.e., memory addresses).

🙂 Happy Learning !

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top