[Python] Getting duplicate Python object memory addresses

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I noticed something when trying to print map object in Python:

    def double(x):
    return 2 * x

    L = [12, 4, -1]

    print(map(double, L))
    print(map(double, L))
    print(map(double, L))
    print(map(double, L))
    print(map(double, L))
    print(map(double, L))


    Here's the result:

    <map object at 0x1025f3f40>
    <map object at 0x1025f3fd0>
    <map object at 0x1025f3f40>
    <map object at 0x1025f3fd0>
    <map object at 0x1025f3f40>
    <map object at 0x1025f3fd0>


    It alternates between 2 addresses: 0x1025f3f40 and 0x1025f3fd0.

    I have read the post on how Python uses the same address for different instances. However, I thought my code should have reproduced the same result as example #1 rather than example #3 in that post?

    Furthermore, I discovered another odd behavior when calling gc.collect() as I suspect it has something to do with garbage collector:

    import gc

    def double(x):
    return 2 * x

    L = [12, 4, -1]

    print(map(double, L))
    gc.collect()
    print(map(double, L))
    gc.collect()
    print(map(double, L))
    gc.collect()
    print(map(double, L))
    gc.collect()
    print(map(double, L))
    gc.collect()
    print(map(double, L))
    gc.collect()


    In the above code, I added gc.collect() after each print statement. And here's the result:

    <map object at 0x100cb3f40>
    <map object at 0x100cb3f40>
    <map object at 0x100cb2230>
    <map object at 0x100cb3f40>
    <map object at 0x100cb2230>
    <map object at 0x100cb3f40>


    It only starts to alternate between 2 addresses after the second print statement! The addresses after the first and the second call are the same.

    I wonder what is going on here?

    Continue reading...

Compartilhe esta Página