2

Here is a simplified version of what I'm trying to do:

class a():
    Requirement = 0
    def func(self, oldlist, x):
        newlist = [None]*3
        newlist = oldlist
        newlist[x]  = b()
        print "Class a"
        g(newlist)


class b():
    Requirement = 1


def g(list):
    for i in range(3):
        if list[i].Requirement==0:
            list[i].func(list,i)

Initiallist=[None]*3
Initiallist[0]=a()
Initiallist[1]=b()
Initiallist[2]=a()
g(Initiallist)      

Instead of trying to express what I expect in words, I made some diagrams that express what in my mind should happen:

enter image description here

Which would imply that the function inside class a should be called 4 times. However, it only gets called 2 times, so it seems that this is happening:

enter image description here

I don't understand why this is happening or how I should fix it.

3
  • 1
    Please correct your indentation of the code in the question. Commented Feb 1, 2013 at 12:37
  • 1
    You'll want to correct your formatting, since this is critical in Python for your program to run as intended. It lets people run it more easily and try it out on their systems. Commented Feb 1, 2013 at 12:39
  • 1
    Yes, I'm sorry. I just fixed it. Thank you for adding the pictures Commented Feb 1, 2013 at 12:43

2 Answers 2

5

Not sure, but I think your problem is this line:

newlist = oldlist

I guess you want to copy the list (and not altering oldlist), so you should simply use:

newlist = oldlist[:]

So changing func to

def func(self, oldlist, x):
    newlist = oldlist[:]
    newlist[x] = b()
    print "".join(x.__class__.__name__ for x in newlist)
    g(newlist)

prints

bba
bbb
abb
bbb

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

1 Comment

remember to tick this as answer if you like it =)
0

In func you need to create a copy of oldlist, otherwise it will modify the same list.

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.