Efficient way to break up a list into two pieces

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Feb 20 20:41:11 EST 2010


On Sat, 20 Feb 2010 17:06:36 -0800, Jonathan Gardner wrote:

> On Sat, Feb 20, 2010 at 4:55 PM, marwie <marwie at gmx.de> wrote:
[...]
>>    l2 = l1[10:]
>>    del l1[10:]
>>
>> But since I'm assigning a slice the elements will be copied. Basically,
>> I'm looking for something like l1.pop(10,len(l1)) which returns and
>> removes a whole chunk of data. Is there such a thing (and if not, why
>> not?)
>>
>>
> The idiom is:
> 
>>>> l1, l2 = l1[:10], l1[10:]

No, that has different behaviour to what the Original Poster wants, AND 
it does two copies instead of one:

(1) copy l1[:10] and l1[10:]
(2) assign the names l1 and l2 to them
(3) if, and only if, there are no other references to the original l1, it 
gets deleted (garbage collected).


What the OP is doing is quite different:

(1) copy l1[:10]
(2) assign the name l2 to it
(3) resize l1 in place to the first 10 items.


What the OP wants is:

(1) assign the name l2 to l1[:10] without copying
(2) resize l1 in place to the first 10 items without affecting l2.


-- 
Steven



More information about the Python-list mailing list