Suggestion: PEP for popping slices from lists

Neatu Ovidiu neatuovi at gmail.com
Thu Aug 8 06:38:18 EDT 2013


On Thursday, August 8, 2013 1:07:16 PM UTC+3, Peter Otten wrote:
> Neatu Ovidiu Gabriel wrote:
> 
> 
> 
> > The list.pop(index) returns the element represented by the index and also
> 
> > reduces the list by removing that element. So it a short one liner for
> 
> > doing both things. But when it comes for popping a slice of the list there
> 
> > is nothing similar for doing in that simple way.
> 
> > 
> 
> > If you want to remove a slice and also reduce the list you will have
> 
> > something like this:
> 
> > 
> 
> > a_list, a_slice = a_list[:size], a_list[size:]
> 
> > 
> 
> > or even worser if you try to do the same for something in the middle.
> 
> > 
> 
> > My proposal is the extension of list.pop for accepting a way for popping
> 
> > slices.
> 
> > 
> 
> > When doing this:
> 
> > 
> 
> > a_list.pop(i,j)
> 
> > 
> 
> > pop will return the slice [i,j] and remove it from the list.
> 
> > 
> 
> > For popping from an index to the end:
> 
> > 
> 
> > a_list.pop(i, len(a_list))
> 
> > 
> 
> > Or even emptying the whole list:
> 
> > 
> 
> > a_list.pop(0, len(a_list))
> 
> > 
> 
> > 
> 
> > So this is it :)
> 
> 
> 
> You'd use 'del' to remove a slice from a list. So:
> 
> 
> 
> >>> def pop_slice(items, *indices):
> 
> ...     x = slice(*indices)
> 
> ...     result = items[x]
> 
> ...     del items[x]
> 
> ...     return result
> 
> ... 
> 
> >>> items = range(10)
> 
> >>> pop_slice(items, 3)
> 
> [0, 1, 2]
> 
> >>> items
> 
> [3, 4, 5, 6, 7, 8, 9]
> 
> >>> pop_slice(items, 3, 4)
> 
> [6]
> 
> >>> items
> 
> [3, 4, 5, 7, 8, 9]
> 
> >>> pop_slice(items, None, None, 2)
> 
> [3, 5, 8]
> 
> >>> items
> 
> [4, 7, 9]
> 
> 
> 
> But what's your use case?
> 
> Does it occur often enough that you cannot afford a two-liner like
> 
> 
> 
> result = items[start:stop]
> 
> del items[start:stop]
> 
> 
> 
> ?


> But what's your use case?
> 
> Does it occur often enough that you cannot afford a two-liner like
I think uses cases are plenty.
And how can I figure out how often it occurs? I don't have a hint, it remains an open question.

The issues I see so far with my proposal are:
  - what you said, how often it is used, if it deserves a place
  - maybe it should be a separate function like pop_slice to don't alter in anyway the behavior of good old pop
  - it will rise some backwards compatibility issues

I just find it's a more pythonic way to deal with this situation. One short line instead of two or one long line is better. This shortness of typing is the core feature of Python so I think my proposal it's leap towards simplicity.



More information about the Python-list mailing list