Syed Mehtab Hassan
Syed Mehtab Hassan

Reputation: 1337

when memory is allocated to variable in python?

As in java

int requires 4 bytes
float requires 4 bytes
char requires 2 bytes

but in python we donot declare type of variable so,

Q. When memory is allocated to the variable?

As in the below example different type of data is allocated to same variable

var = 10
print var
print type(var) #<type 'int'>

var = 10.5
print var
print type(var) #<type 'float'>

var = "python"
print var
print type(var) #<type 'str'>

Upvotes: 1

Views: 716

Answers (1)

user4815162342
user4815162342

Reputation: 154916

The memory for the variable is allocated when the variable is created - e.g. when you enter the function, in case of local variables.

The memory for the object is allocated when the object is created, regardless of whether it is assigned to a variable.

In Java terms, you can think of all Python variables as holding references to Objects. This means that each variable only requires a fixed pointer-sized amount of memory to "hold" (refer to) its contents. That's why Python variables can easily refer to data of different type throughout their lifetime.

Upvotes: 3

Related Questions