in place-ness of list.append

Bart Van Loon bbbart at inGen.be
Mon Feb 5 06:11:48 EST 2007


It was Mon, 5 Feb 2007 05:01:28 -0600, when skip at pobox.com wrote:
>
>     Bart> #--------------------------------------------------
>     Bart> def addnumber(alist, num):
>     Bart>     """ work around the inplace-ness of .append """ 
>     Bart>     mylist = alist[:]
>     Bart>     mylist.append(num)
>     Bart>     return mylist
>     Bart> #--------------------------------------------------
>
>     Bart> and I am wondering if this is good practice or not.
>
>     Bart> any advice on this matter?
>
> Such an operation will be O(N**2), 

why is that?

> and thus expensive if performed frequently on lists of moderate
> length.  I've never been tempted to do this.  Can you say a little
> about why you'd want to do this?  Knowing that, perhaps someone here
> can point you in a more Pythonic direction.

I am building a binary tree where each node is a list. the two children
are the parent list + 1 and the parent list + 2.

I am using it recursively as such:

#-----------------------------------------------------------
def makescoretree(scorelist):
    """ generates the Tree of possible scores """
    if waves(scorelist) >= MAXWAVES:
        return []
    return Scoretree(scorelist, 
                     makescoretree(addnumber(scorelist, 1)),
                     makescoretree(addnumber(scorelist, 6)))
#-----------------------------------------------------------

but now I found out that I can do this easily like

#-----------------------------------------------------------
def makescoretree(scorelist):
    """ generates the Tree of possible scores """
    if waves(scorelist) >= MAXWAVES:
        return []
    return Scoretree(scorelist, 
                     makescoretree(scorelist + [1]),
                     makescoretree(scorelist + [6]))
#-----------------------------------------------------------

-- 
regards,
BBBart

   "Who can fathom the feminine mind?" -Calvin "I like `em anyway" -Hobbes



More information about the Python-list mailing list