Hi
Trying to learn Python here, hope its ok to ask basic non blender releated questions ?
I was just puzzled by a bit of code I had written to nest a list inside a list. The inner list variable I was using, I added to the outer list, then changed the inner list variable, only to notice that the outer list, also changed at that point to reflect the change. (Not what I wanted it to do)
I guessed this was a probably a shallow/deep copy issue, my attempt at a fix was to import the copy module and add a line
2 Questions
Q1 Was my assumption about the problem correct ?
Q2 This seemed a bit convoluted, is there a simpler way of achieving the same end result ?
Hi Craven
You would have been even more confused by the question if I had posted the routine it was in . Here is a simple example of the same thing
a = [1,2,3]
b = [2,3,4]
c= []
c.append(a)
c.append(b)
print c
b.pop()
print b # b drops the 3rd element
print c # c also follows the effect on b, presumably as its a shallow copy ??
You are correct! When you say “foo = [1,2,3]” foo is then a pointer to the list not the list itself. So when you append a to c you are putting the pointer in the list c.
A quicker way to make sure a new, unreferenced, list is put into c is to append a[:]. That is a slice of a from the beginning to the end (the whole thing).
This is an important and subtle point with Python lists - knowing when you are working with the original or a copy. Some list method (and string methods) work ‘in-place’ while others return a new modified object.