[Python] I'm confused about how objects in shallow copy and deep copy are referenced

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Shallow_Copy

    foo = [1, 2, []]
    bar = foo.copy()
    foo[0] is bar[0]
    foo[2] is bar[2]


    True
    True


    Does this mean they both reference to the same objects? However, they behave differently when I modify them.

    bar[0] = 0
    print(foo)


    [1, 2, []]


    bar[-1].append(3)
    print(foo)


    [1, 2, [3]]


    if foo[0] and bar[0] are referencing the same object, when I modified bar[0] why did foo[0] stay the same? And when I modified bar[2], foo[2] changed

    Deep_Copy

    foo = [1, 2, []]
    bar = copy.deepcopy(foo)
    foo[0] is bar[0] foo[2] is bar[2]


    True
    False


    Additionally, why foo[2] and bar[2] don't reference the same object here

    Continue reading...

Compartilhe esta Página