Efficient way to break up a list into two pieces

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Feb 21 01:48:36 EST 2010


On Sat, 20 Feb 2010 21:21:47 -0800, Jonathan Gardner wrote:

> On Sat, Feb 20, 2010 at 5:41 PM, Steven D'Aprano
> <steve at remove-this-cybersource.com.au> wrote:
>>
>> 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.
>>
>>
> For ten items, though, is it really faster to muck around with array
> lengths than just copying the data over? Array copies are extremely fast
> on modern processors.

My mistake, he actually wants l1[10:] copied. So you might be copying a 
huge amount of data, not just ten items.

Or if you prefer, replace 10 by 100000000.

But in either case, I agree that *in practice* it's rarely an actual 
problem.


> Programmer time and processor time being what it is, I still think my
> answer is the correct one. No, it's not what he says he wants, but it is
> what he needs.

You missed the point that your suggestion gives radically different 
behaviour to what the OP indicated he is using. He mutates the list in 
place, you rebind the list's name. That has *very* different semantics.


>>> a = b = [1, 2, 3, 4]
>>> del a[2:]  # mutate in place
>>> b
[1, 2]
>>>
>>> a = b = [1, 2, 3, 4]
>>> a = a[2:]  # rebind the name
>>> b
[1, 2, 3, 4]

The OP may not care about the difference, but if he does require the 
first behaviour, then your solution doesn't help.


-- 
Steven



More information about the Python-list mailing list