+ 4
Python ID Mystery
I have stumbled upon something surprising. Does anybody know what's going on here? (Details in code.) https://code.sololearn.com/ceg91PiC9O0H/?ref=app
3 Answers
+ 4
HonFu
For mutable types:
id( [ ] ) == id( [ ] ) #true
id( [5,2,1] ) == id ( [5,2,1] ) #true
a = []
id( a ) == id ( [ ] ) # false
For inmutable types it's like Mirielleđ¶ [Inactive] said:
a = 6
id( a ) == id( 6 ) #true
+ 2
It allows it for immutable types like int or string, but according to the specification, mutable types are treated differently.
Look at part 3 and part 4 of my ecample again:
In part 3, two individual lists are created, and obviously they have different IDs, the test confirms it.
In part 4, logically, the ids of two individual lists would have to be stored - but it is two times the same.
+ 2
Yeah, Kevin, but that much became obvious in the code already. (And immutables weren't the topic in the first place.)
The question is why?
The two lists, that are created, are created one by one, left to right, and they're mutable, so they should get different IDs, and after the IDs have been identified, the garbage collector should get rid of both.
But it does not seem to play out like that... Somehow the procedure must be different.