1

Why is this not working as expected (at least for me)? I can't figure why.

class Fred:
    def __init__(self):
          self.a=0

fred=Fred()
lista=[]

for i in range(5):
    fred.a=i
    lista.append(fred)

for i in lista:
    print(str(i.a))

All I get is 5 times the number 4 and not from 0 to 4. Any comments? Thanks

1
  • 1
    this is bcoz all the elements in lista are referencing to the same element,, and the you see the number 4 since its the latest updated value of the object fred Commented Oct 28, 2012 at 4:46

2 Answers 2

1

What is happening is that the reference to Fred is being overwritten each time you loop in the for i in range(5). If you move the fred=Fred() inside that loop and create a new object each time, then you should see the expected result.

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

Comments

0

You've got one Fred instance and keep adding that one instance to the list, changing its a property while you do that. Adding to the list does not copy the Fred object; it just adds another reference to the same object. You can get your expected behavior by creating a new Fred inside each iteration of the loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.