Fast Efficient way to transfer an object to another list

Francesco Bochicchio bieffe62 at gmail.com
Sat May 1 11:11:45 EDT 2010


On 1 Mag, 05:35, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:

>
> def transfer_stock(stock_code, old_list, new_list):
>     """ Transfer a stock from one list to another """
>     while True:  # loop forever
>         try:
>             i = old_list.index(stock_code)
>         except ValueError:
>             # not found, so we're done
>             break
>         new_list.append(old_list[i])
>         del old_list[i]
>     return new_list
>
> --
> Steven

I think this could be slower than doing like the OP, since  'index'
rescan the whole list every time
while doing an explicit loop you only scan the list once.

Anyway i think that list.extract( old_list, predicate ) -> new_list
would be a nice addition to the standard library
(possibly a C faster version of what one could implement in
python) ... and since the library is not under moratorium
maybe we will have it ...  the semantic could be like th OP asked:

--- code begins

class ListE(list):
    def extract(self, predicate):
        res = []
        for idx, el in enumerate(self):
            if predicate(el):
                res.append( self.pop(idx) )
        return res

class Stock(object):
    def __init__(self, code):
        self.code = code
    def __repr__(self): return "Stock: code=%d" % self.code

l = ListE( Stock(n) for n in range(19) )

subl = l.extract( lambda x: x.code in (1,4, 9) )

print " l = ", l
print  "subl = ", subl

--- code ends
--- results

 l =  [Stock: code=0, Stock: code=2, Stock: code=3, Stock: code=5,
Stock: code=6, Stock: code=7, Stock: code=8, Stock: code=10, Stock:
code=11, Stock: code=12, Stock: code=13, Stock: code=14, Stock:
code=15, Stock: code=16, Stock: code=17, Stock: code=18]
subl =  [Stock: code=1, Stock: code=4, Stock: code=9]




Ciao
---
FB



More information about the Python-list mailing list