[Python-ideas] pop multiple elements of a list at once

Guido van Rossum guido at python.org
Mon Jul 12 08:35:13 CEST 2010


On Sun, Jul 11, 2010 at 7:58 PM, Diego Jacobi <jacobidiego at gmail.com> wrote:
> I guess that it would be improved if i can just pop a defined number
> of elements, like this:
>
> pop self.recv_buffer[:-size]
> or
> self.recv_buffer.pop(,-size)
>
> That would be... "pop from (the last element minus size) to (the last element)"
> in that way there is only one memory transaction.
> The new list (or maybe a tuple) points to the old memory address and
> the recv_buffer is advanced to a one new address. Data is not moved.

I think yo misunderstand the implementation of lists (and the
underlying malloc()). You can't break the memory used for the list
elements into two pieces and give new ownership to a (leading) section
of it. However you also seem to be worrying about "copying" too much
-- the only things that get copied are the *pointers* to the objects
popped off the stack, which is very cheap compared to the rest of the
operation. It is true that to pop off a whole slice there is a more
efficient way than calling pop() repeatedly -- but there's no need for
a new primitive operation, as it can already be done by copying and
then deleting the slice (again, the copying only copies the pointers).

Try reading up on Python's memory model for objects, it will be quite
enlightening.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list