0

I have a small piece of code where I am trying to change the member values of an array of class objects.

class Test(object):
    def __init__(self):
        self.id = 0

test = []
temp = Test()

for i in range(5):
    temp.id = i
    test.append(temp)
    print(test[len(test)-1].id)

print()

for i in range(5):
    print(test[i].id)

However, I am getting the following result and I'm unable to figure out why? Any help is appreciated.

0
1
2
3
4

4
4
4
4
4
1
  • 1
    You only have one Test object. You'll have to create more of them. Commented Mar 31, 2020 at 15:15

3 Answers 3

1

You are overriding id field on your temp object and later you are appending it, so your list will contain the same object multiple times.

What you need is to create a new Test() object on every iteration:

for i in range(5):
    temp = Test()
    temp.id = i
    test.append(temp)
    print(test[-1].id)

The reason it prints the correct output for the first run is because you are printing the newly created id and while you are not inspecting the previous values.

If you would add a print for the list, you would see that the id field is changing for all.

Sign up to request clarification or add additional context in comments.

Comments

0

This is normal. You filled test with the same object at each step and you are modifying this object. Whenever you do a modification all the references of the object are modified. To see this you can print the id of temp at each step

class Test(object):
    def __init__(self):
        self.id = 0

test = []

for i in range(5):
    temp = Test()
    temp.id = i
    test.append(temp)
    print(test[len(test)-1].id)

for i in range(5):
    print(test[i].id)

And the output will be:

0
1
2
3
4

Comments

0

or you can use copy module. even a shallow copy seems to do the trick.

add an import on top.

import copy

and modify your line

test.append(temp)

to

test.append(copy.copy(temp))

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.