Objects vs Variables
Life with Python #6
What are variables and objects in Python, you ask? We have all heard of them. We all know them too, in a manner of speaking. Aren’t they pretty much the same thing, really? I am not ashamed to admit that I was almost convinced of it.
However, the answer it turns out is “almost, but not quite”. It is important to understand and appreciate the subtlety of this difference if one is to become a good python practitioner. So here we go!
- Objects
An object is an instance of a data type that resides in memory and has properties (attributes) and behaviours (methods). In Python, every data element (eg: number, string, list, tuple or custom data type) is in fact an object. All objects are created from classes, which define their structure and behaviour.
Get Prathik C’s stories in your inbox
Join Medium for free to get updates from this writer.
Each object in python has three characteristics which uniquely distinguish them:
- Identity : typically refers to the memory location of the object. It is the only read-only characteristic of python objects. We can use
id()to retrieve this information. - Value : it is the concrete data held by the object (like
str,intorfloatvalue). - Type : determines which class the object is derived from. We can use
type()to determine the type of any object. We can also get this information by directly accessing the__class__attribute which exists for any object in python.
x = 10
id(x) # some number like 4343440904 referring to the memory location.
type(x) # <class 'int'>
x.__class__ # <class 'int'>- Variables
A variable is essentially a name or label that refers to an object stored in memory. So, they don’t contain the actual data; they simply act as pointers or references to the objects which do. Moreover, they can be reassigned to refer to new/different objects, but the objects themselves remain unaffected by this reassignment.
Consider the following code for an illustration of the above:
a_variable = [1, 2, 3] # a_variable references a list object
b_variable = a_variable # b_variable also points to the same list object
a_variable = 10 # a_variable is reassigned to an int object
b_variable.append(4) # 4 is appended to the list object
print(a_variable) # 10
print(b_variable) # [1, 2, 3, 4]Everything is summarized in the following table:
Until next time! :)










