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

Steven D'Aprano steve at pearwood.info
Tue Aug 27 07:24:25 CEST 2013


On Mon, Aug 26, 2013 at 11:07:00PM +0200, Sébastien Volle wrote:
> List comprehension works too:
> 
> my_list = [ thing for thing in my_list if thing not in things ]
> 
> But both our solutions don't change my_list in place but require creating a
> new list, and would not be very practical with big lists.

That's true, but it is remarkable how on a modern computer, Python's 
idea of "big" is so different from what the average coder considers big.

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:

mylist[:] = [x for x in mylist if not condition(x)]

Just common sense, right? In a fit of premature optimization, I 
started writing:

N = 1000  # take a wild guess
if len(mylist) > N:
    ... # inplace deletion
else:
    ... # copy and slice


Then I decided to systematically determine the value of N. I have not 
been able to. Copy and slice is always faster, in my experience. If 
there is such an N that counts as "big" in this sense, it is probably so 
big that I'm not able to create the list in the first place. So that 
probably means hundreds of millions of items, or more. Certainly not 
what the average coder thinks of as "a big list", say, a couple of 
screens full of items when printed.


> Anyway, I'd rather stick with the simple for loop than making list methods
> too clever.

+1 

We are agreed :-)



-- 
Steven


More information about the Python-ideas mailing list