Basic Python Question

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

tempCopy = copy.deepcopy(onePath)

This did make it behave as I was expecting,

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 ?



I’m a bit confused as to what you are trying to do, can I see a code snippet, python is so much easier than English…

Hi Craven
You would have been even more confused by the question if I had posted the routine it was in :smiley: . Here is a simple example of the same thing

a = [1,2,3]
b = [2,3,4]
c= []
print c
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.