[Python-ideas] Allow multiple arguments to `list.remove` and flag for silent fail

random832 at fastmail.us random832 at fastmail.us
Tue Aug 27 07:37:11 CEST 2013


On Tue, Aug 27, 2013, at 1:24, Steven D'Aprano wrote:
> When I was starting out with Python, I wrote code like I learned to code 
> using Pascal:
> 
> for i in range(len(mylist)-1, -1, -1):
>     if condition(mylist[i]):
>         del mylist[i]
> 
> Since that's an inplace deletion, it seems like it should be cheaper 
> than making a copy of mylist:

That's the wrong way to do it - each time you delete an item, you're
moving everything behind it by one space. The fact that you're iterating
backwards doesn't solve that issue. The _right_ way to do it, as far as
there is a right way, is:

dst=0
for item in mylist:
   if not condition(item):
      mylist[dst] = item
      dst += 1
mylist[dst:]=[]

This avoids moving any item or resizing the list more than once, and is
therefore O(n).


More information about the Python-ideas mailing list