Python Forum
Unwanted variable change in module - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unwanted variable change in module (/thread-10000.html)



Unwanted variable change in module - dannyH - May-08-2018

I have a module that takes 2 lists and creates a new list from them, but somehow it manages to change one of the input lists when I don't want it to:
def repeatAddCode(newList, oldList):

# Version:  2.0 D Higgins 07/05/2018
# Input:    a) A List of lists of the latest code numbers.
#           b) A List of lists of the original raw code numbers.
# Function: If the last two numbers in a code from newList equal
#           the first two numbers in a code from oldList, add another
#           level of extended numbers.
# Output:   A new list of codes.

    returnList = []
    
# The position of the first column in a code row is stored as Lx[-2]
# and the position of the last column in a code row is stored as Lx[-1].
    for new in newList:
        newStart, newStop = new[-2], new[-1]
        for old in oldList[:]:
            oldStart, oldStop = old[-2], old[-1]
            if oldStart == newStart + 1 and old[oldStop - 1] == new[newStop] and old[oldStop - 2] == new[newStop - 1]:
                for entry in oldList:
                    print '#', entry
                new[newStop + 1] = old[oldStart + 2] # This line changes oldList
                for entry in oldList:
                    print '##', entry

    return returnList
What am I doing wrong?


RE: Unwanted variable change in module - killerrex - May-08-2018

You are changing the content of new, that is a list inside newList... and it might be what you whant to do (although your returnList is empty)
I suspect that when you have created the newList in the code that call your repeatAddCode you are doing something like:
newList = oldList[:]
And that create a new "list wrapper" but the id of all the sublist are the same.
To confirm it you can use:
print([id(new) for new in newList])
print([id(old) for new in oldList])
If some id are equal, whatever you do to that element in newList will also happen in oldList.

If you want to create a full copy of the list take a look to the copy module and the deepcopy operation.


RE: Unwanted variable change in module - dannyH - May-08-2018

Many thanks for the reply.
In my main program I had the line:
next1 = old1[:]
before I called the module, which I thought would be OK. copy.deepcopy() solves the problem.


Regards, Danny