Problems with copies (and references) to lists

bvdpoel at uniserve.com bvdpoel at uniserve.com
Wed Apr 17 20:12:28 EDT 2002


Took awhile, but I do have the following bit of code working as it
should. The doc string is misleading, but I'm not sure of how better to
describe it out of context... The important thing is, it is giving the
right result, and it is NOT changing the original list.

-------
def doubleUp(a, fact):
        """ Makes fact/2 copies of list [ [s, l, v,...] ].
                New copy has all values of l divided by fact/2 and
                copies of s set to s/2 and 50+(s/2).
		fact will always be a power of 2.
        """

        new = a
        while fact >1:
                b1 = []
                b2 = []
                for t in new[:]:
                        n=t[:]          # this prevents munging our
original
                        n[0] /= 2
                        n[1] /= 2
                        b1+=[n[:]]      # [:] forces new copy of n!
                        n[0] += 50
                        b2+=[n]
                fact /=2
                new = b1 + b2
        return new

a = [[0.0, 20.0, 66, 44],[50.0, 20.0, 55, 33]]
print doubleUp(a, 2)
print doubleUp(a,4)
print a

--------

But, I'm wondering if it is at all efficient. Or even good python. Seems
that the number of [:] needed just makes for ugly code.

-- 
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at uniserve.com
WWW:   http://users.uniserve.com/~bvdpoel




More information about the Python-list mailing list