Python List Issue

Nick L Fearnot003 at mchsi.com
Sun Mar 27 04:01:20 EST 2005


I've hit a brick wall on something that I'm guessing is pretty simple but
it's driving me nuts. I noticed that with python lists, generally when you
make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
List2 and any modifications done to List1 affects List2. Ok I can live with
this but I want to make a completely seperate copy not attached to the
original in anyway. So then I used this method. List1 = List2[:]  .  This
seemed to work in most situations, here I can modifiy List1 with out it
affecting List2. But now I've run into an odd problem, and I have no idea
why it's doing what it's doing.
Here's some code

#some globle varibles
bob = [[[0, 0]]]
final = []

########################
def ApplySourceFunc(bob, final):
    for I in range(1):

        for I in range(len(bob)): #will go through the list and apply
            ApplyOperatorsLoop(bob[I][:]) #all the operators to each rule in
the list creating a new list of rules

        bob = final
        final = []
#end ApplySourceFunc######

########################
def ApplyOperatorsLoop(aList):

    iTemp = [] #initial temp, just for validity checking

    iTemp = AddGetSpeed(aList[:])
    if not iTemp == None: #if the operator returns None, then nothing of
value happend
        final.append(iTemp)

#end ApplyOperatorsLoop####

#########################
def AddGetSpeed(tList):
    ln = len(tList) #get the length of tList

    if ln > 0:
        if tList[ln-1][0] == 0:
           tList[ln-1][0] = "GetSpeed()"
            print "New Rule 'GetSpeed()' Added to the List"
            return tList
    return None
#end AddGetSpeed#########

So, here's what going on. ApplySourceFunc calls ApplyOperatorsLoop which
calls AddGetSpeed. Each function passes the list bob to the next fuction
using the [:] method. For some reason when I get to the AddGetSpeed method
and I do the assignment " tList[ln-1][0] = "GetSpeed()" " this directly
modifies the list bob. Ok, so i was annoyed by that since I was using the
whole [:] method as I passed and used the lists. Then I tried to insert a
temp list into the ApplyOperatorLoop function ( temp2 = aList[:]) and then
pass that into AddGetSpeed. Even when I did this AddGetSpeed modified the
orginial bob list. so, what I'm getting down to is:
    How on earth can I make a complete seperate copy of a list with out it
being a attached to the original in any way shape or form so that I can
modifiy if at will and not worry about the original? I've tried every
combonation that I can think of to get this to work, I even wrote my own
copy function but even then I had the same trouble. Until this point
everything was going good, but this has really bugged me

Any ideas, suggestions, comments are greatly appreciated
thanks

Nick





More information about the Python-list mailing list