Suggestion: PEP for popping slices from lists

Terry Reedy tjreedy at udel.edu
Thu Aug 8 16:03:27 EDT 2013


On 8/8/2013 7:44 AM, Neatu Ovidiu wrote:

Objection 1. People usually want to chunk sequences, not lists 
specifically. We now try to add new features that work with iterators 
and iterables generally, not just lists.

> This can be useful for doing all kinds of basic stuff. For example if you wanted to take 4 items of a list at at a time, do something with them and then update the list.
>
> jobs = ['job1', 'job2', 'job3', 'job4', 'job5', 'job6', 'job7', 'job8', 'job9', 'job10']
> while jobs:
>      print(jobs.pop_slice(0,4))
>
> should output
>
> 'job1', 'job2', 'job3', 'job4'
> 'job5', 'job6', 'job7', 'job8'
> 'job9', 'job10'

Objection 2. Usually when one wants to do this sort of thing, one wants 
the list either be intact or empty at the end. Emptying it chunk by 
chunk is worse than useless because it turns an O(n) process into an 
O(n*n) process.

The same is true of destructively iterating through a list with .pop(0). 
When I proposed the addition of .pop(), I meant it as the inverses of 
.append and did not include the (optional) index parameter. It is seldom 
used and usually only once, to remove a single leading item. The 
addition of iterators, which occurred *after* the addition of .pop, 
replaced some uses of .pop(0). For instance

first = mylist.pop(0)  # O(N) operation
for item in mylist:
   process(first, item)
del mylist

can, since 2.2, be written as

it = iter(mylist)
first = next(it)  #  O(1) operation
for item in it:
   process(first, item)
del mylist

If .pop were being added today, I would argue against including the 
index parameter.

-- 
Terry Jan Reedy




More information about the Python-list mailing list