[Python] When appending object of a class to a list, whole list are overwritten by last...

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

  1. Stack

    Stack Membro Participativo

    When appending an instance of a class to a list, whole list are overwritten by last object. Which other option we have if we don't want to use "deepcopy"

    class Person:
    def __init__(self):
    self.age = None

    list_of_lists = []
    p1=Person()

    p1.age=40

    list_of_lists.append(p1)

    p1.age=20
    list_of_lists.append(p1)


    for objpid3 in list_of_lists:
    print(objpid3.age)


    Result

    20 20

    Expected result

    40 20

    Continue reading...

Compartilhe esta Página