[Python] When appending a item to a propriety of type list of a object inside a list, that...

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

  1. Stack

    Stack Membro Participativo

    When appending a item to the pros propriety, which is of type list, in a object inside the objs list, which have two objects, both of type Car, it seems that the two variables are linked somehow. And what i mean by that is, when appending a item, which in the case of the code bellow corresponds to the string Is fast and Is spacious, the effect is reflected in both, even though the variables are from distinct objects.

    The code:

    class Car():
    def __init__(self, model, pros = [], cons = []):
    self.model = model
    self.pros = pros
    self.cons = cons

    objs = [ Car('Ferrari'), Car('Corsa') ]

    objs[0].pros.append('Is fast')
    objs[1].pros.append('Is spacious')

    for i, obj in enumerate(objs):
    print(f'Index: #{i} ')
    print(f'Model: {obj.model}')
    print(f'Pros: {obj.pros}')
    print(f'Length: {len(obj.pros)}')


    Output:

    Index: #0
    Model: Ferrari
    Pros: ['Is fast', 'Is spacious']
    Length: 2
    Index: #1
    Model: Corsa
    Pros: ['Is fast', 'Is spacious']
    Length: 2


    Expected Output:

    Index: #0
    Model: Ferrari
    Pros: ['Is fast']
    Length: 1
    Index: #1
    Model: Corsa
    Pros: ['Is spacious']
    Length: 1

    Continue reading...

Compartilhe esta Página