0

When I run this code

def outer():
    xs = {1,2,3,4,5,6,7,8,9,10,11}
    print(xs)
    print(id(xs))
    xid = id(xs)
    def inner():
        xs = {1,2,3,4}
        print(xs)
        print(id(xs))
        yid = id(xs)
        print(xid == yid)
    return inner


fn = outer()
fn()

xid and yid value is the same in intellij,

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
140317084319328
{1, 2, 3, 4}
140317084319328
True

but when i run in a terminal

>>> fn = outer()
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
140343083023728
>>> fn()
{1, 2, 3, 4}
140343082597504

they are different. I am expecting that yid should be different because there is no interning happening for a list. Can anyone explain this behaviour

Srinivas
  • 2,010
  • 7
  • 26
  • 51
  • TL;DR: *implementation details.* The set does go out of scope after `outer` is done, so its memory location *can* be reclaimed, but *does not have to*. For some reason or another, Python internally reuses the memory location in one case but not in a very different situation. You'll have to dig through the implementation details if you really want to figure out why, but I'm not sure what that exercise would be useful for. – deceze Mar 02 '22 at 07:10
  • @deceze, I agree with your answer. but that link that was shared, does not answer this question. – Srinivas Mar 02 '22 at 07:15

0 Answers0