Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutability in Python [duplicate]

I trying to understand how the immutability works in python. Since string are immutable in python, I was expecting the id to change every time I perform a string operation but it doesn't work as expected. example: The last operation on t doesn't change its id. Any ideas why?

Screen shot of the operation

like image 601
Newbie Avatar asked Feb 21 '17 16:02

Newbie


1 Answers

I had a row of apples in different cells [memory containing variables (I will not go to the bit level)], of which some were empty [cells containing garbage / empty value].

I took one out. It was in cell 3 [logical address = 3].

I painted it blue (after I cloned it using future tech, for immutability demonstration) [committed an operation on it, same could go for addition for integers].

I looked where to put it, and although cell 4 was free, cell 3 was also (because the "original" apple is not here anymore)! So I put it back in cell 3 [and although we get a "new" apple, it has the same address].


Same goes for your t (note that id is the memory address of the variable in CPython), but since we are talking about "chains of apples" here (strings are made of a characters sequence, we have to consider the amount of space we have to continue the sequence, so if I had my memory looking like (_ stands for arbitrary garbage data, '^' for space)

H e l l o _ _ _ _ _ B O O M
^ string pointer points here

and I wanted to change the string to "Hello you", I might consider using the free space:

H e l l o ^ y o u _ B O O M
^ string pointer points here

But if I want to change the string to "Hello world!", I would have to look for free space in the length of "Hello world!" somewhere else (we might have it right after "BOOM", which is probable in a garbage collected environment, look at how your IDs differs):

H e l l o ^ y o u _ B O O M _ H e l l o ^ w o r l d ! _ G A R B A G E
                              ^ string pointer points here
like image 69
Uriel Avatar answered Sep 22 '22 09:09

Uriel