0

Basically, this is what the problem is. I have a class with an optional parameter: lst. lst is a nested list. Below is a method that returns another instance of the class that it is inside.

self.lst = [[[1, 2]]] # this is defined in the constructor
s = self.lst
for a in s:
    for b in a:
        if b[0] != item:
             b[0] = 5
return ChangeNumb(lst=s)

What happens after this is VERY weird. Returning ChangeNumb.lst is now [[[5, 2]]], but the class that the method is run in ALSO ChangeNumb.lst == [[[5, 2]]].

So that instead of just returning a new instance of a class with a different parameter, this method changes the self.lst of the class it is inside as well.

I need to make it so that self.lst does not change, while returning a new instance.

PLEASE HELP

EDIT: Although I've encountered a similar problem when writing the class constructor, I was able to resolve it as -> self.lst = lst.copy(); however, s = self.lst.copy() does not work!

5
  • list.copy isn't a method that exists. To copy a list, you can just slice it: lst[:]. Commented Feb 25, 2015 at 7:39
  • list.copy() runs because it's a method of a list object; I've just tried lst[:] but it's the same result. Commented Feb 25, 2015 at 7:42
  • @mgilson: It was introduced in 3.3. Commented Feb 25, 2015 at 7:46
  • The slice copy will not work in this case, it just copies the reference, use copy.deepcopy() Commented Feb 25, 2015 at 8:06
  • @user2357112 -- Thanks. I knew it was proposed, (and I think it's a good decision to add it). I'm glad you mentioned it to document for others who come across this post. Commented Feb 25, 2015 at 14:43

1 Answer 1

2

You have to make a copy in order not to modify self.lst.
For simple lists just list() is enough, but as you have nested lists you should use copy.deepcopy().

So you could change your declaration with something like :

s = copy.deepcopy(self.lst)
Sign up to request clarification or add additional context in comments.

3 Comments

I think you need to copy the list before it is mutated in the loop. Try s = copy.deepcopy(self.lst), then keep the return as it was.
Can you explain to me how I can use deepcopy? Cause I've tried a = [[1]] b = a.deepcopy() but it just returns AttributeError: 'list' object has no attribute 'deepcopy'
@Charlie: import copy then b = copy.deepcopy(a)

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.