[Python-ideas] Proposal how to remove all occurrences of a value from a Python list

Steven D'Aprano steve at pearwood.info
Sun Oct 4 15:22:03 CEST 2015


On Sat, Oct 03, 2015 at 06:05:26PM +0300, Eduard Bondarenko wrote:
> Hello everyone,
> 
> the main idea of this proposal is to create convenient, maybe more Pythonic
> way to remove all occurrences of a value from a Python list.

What's so special about removing all occurances from a list? How often 
do you find yourself doing such a thing?

These aren't rhetorical questions. They're questions that need to be 
answered before your proposal can be turned into a new feature. If the 
answer is "not very special, and only rarely" that won't necessarily 
rule out the change, but it will make it harder to convince that it is 
desirable.


> Suppose we have list 'arr':
[...]
> Looks good, at least for experienced developer, but for Python's newcomers
> solution will look like this:
> 
> >>> while True:
> ...     try:
> ...         a.remove(1)
> ...     except:
> ...         break

Part of the process of learning to be a programmer is learning to avoid 
awful code like the above and instead learn general purpose processing 
techniques like the list comp. In my experience, e beginner is more 
likely to come up with this:

while 1 in arr:
    arr.remove(1)


since it is far more straight-forward than your version, and involves 
fewer concepts ("what's try...except do?").


> I was surprised that Python doesn't have easy way to remove all 
> occurrences. 

That depends on what you mean by "easy". Or "obvious". I would consider 
the list comp to be both. But of course, I don't expect beginners to see 
things the same way.


> Currently I am reading "Effective Python" book and I have 
> encounter good idea that it's also important to have readable code for 
> new or another-language developers. And to my mind current Pythonic 
> 'remove all occurrences' is not readable code and does not give 
> insight (at least at first glance) into what happens in the code.

I disagree. The list comp *does* give insight into what happens in the 
code: you iterate over the existing elements of the list, collecting 
the ones which don't equal 1, and then save them back into the list. 
Whereas your suggestion:

> This way looks a little bit nicer. I think so..
> 
> a.remove(1, all = True)

is just a mysterious method call. What insight does it give? How does it 
work? There is no hint, no clue. It might as well be magic.

On the other hand, once the programmer can reason about the task well 
enough to write the list comprehension, they can easily extend it to 
slightly different tasks:

# Skip the first 8 items, then remove numbers less than 5:
arr[9:] = [x for x in arr[9:] if x >= 5]

Your remove(all=True) method cannot be extended and teaches the 
programmer nothing except how to solve this one problem.


-- 
Steve


More information about the Python-ideas mailing list