Fast Efficient way to transfer an object to another list
Tim Chase
python.list at tim.thechases.com
Sat May 1 09:19:00 EDT 2010
On 04/30/2010 10:35 PM, Steven D'Aprano wrote:
> If you know there is one, and only one, item with that stock code:
>
> def transfer_stock(stock_code, old_list, new_list):
> """ Transfer a stock from one list to another """
> i = old_list.index(stock_code) # search
> new_list.append(old_list[i]) # copy
> del old_list[i] # delete
> return new_list
This could be written as
def move(code, source, dest):
dest.append(source.pop(source.index(code)))
return dest
depending on how one thinks. I tend to prefer
lst.pop(idx)
over
tmp = lst[idx]
del lst[idx]
only using the latter if "idx" is a range/slice.
Though since the function mutates the arguments, I'd be tempted
to return None like list.sort() does for the same rationale.
If more than one item is in the source, it will move/remove the
first leaving the remainder; if no matching item is in the source
it will appropriately raise a ValueError.
-tkc
More information about the Python-list
mailing list