python

Variables in Python

In this tutorial we will learn about Python Variables and their working in Python.


Understanding of Python variables:

In Python, a variable is a reserved memory location to store values.
A variable is like a container to store certain values. While the program is running , variables are accessed and they are changed sometimes, i.e a new value will be assigned to a that variable.


How Variables in Python are different than other Languages?

How variables work in C?

In C language whe we declare a vairable and assign value to it then some space is created in memory by the given name and the given values is stored in it. Suppose we write the statement int a=42;, then the following will be the memory diagram



Now if we declare another variable , with the same value ,then again the same process will take place.

Suppose we write,int b=42;


Finally we assign a new value to an existing variables, then it's previous value gets overwritten

Suppose we write,a=43;



How variables work in Python?

In python when we assign value to a variable , then things are different than C.Suppose we write a=42 in python , then python will create 2 things:



Now if we create another variable called b and assign it the same value, then Python will do the following :


Finally if we assign a new value to the variable a,then like C,python will not overwrite the value. Rather it will do the following:


This behaviour of object in python is called "immutability". In other words when we cannot change the value of an object , we say it is immutable , otherwise we say it is mutable. Objects of biult-in type like(int, float, str, bool, complex,tuple) are immutabel. Objects of built -in type like(list, set, dict) are mutable


String are also immutable

String objects in python are also immutable.That is , once we have created a String object, then we cannot overwrite it's value.Although we can change the value of the String refernce by assigning it new String.



Summary