0

I have a simple question: Say that I have the following class:

class step:
    alpha = []

and my main has the following:

listofstep = []

for i in range(20):
    z = step()
    z.alpha.append(0)
    listofstep.append[z]

why does len(listofstep[0].alpha) gives me 20?

user103052
  • 51
  • 1
  • 2
  • You have written inside a for loop which iterates for 20 times and each time it iterates it appends the value which results in printing the `len` as 20. – d-coder Oct 23 '14 at 08:09
  • @Bakuriu I don't think this is a duplicate, or rather the correct one - as the knowledge of the difference between a class and instance variable is the basis for the question you linked, and is the source for misunderstanding here. – Korem Oct 23 '14 at 08:12
  • 1
    @Korem I've should have probably used [this](http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances) question as target. However, since the question *is* a duplicate I'm keeping it closed. If someone else with a dupehammer wants to use the better target *he* can reopen + re-close the question. If I reopened it now I wouldn't be able to close it again, and I don't want to leave it open since it has already been asked over and over. – Bakuriu Oct 23 '14 at 08:24

1 Answers1

0

As you define it, alpha is a class variable and not an instance variable. When you do z.alpha it always points at the same list, regardless of which instance it is. Try to define step like this:

class step:
    def __init__(self):
        self.alpha = []
Korem
  • 11,383
  • 7
  • 55
  • 72