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

Alexander Walters tritium-list at sdamon.com
Sun Oct 4 00:31:26 CEST 2015



On 10/3/2015 17:54, Terry Reedy wrote:
> On 10/3/2015 11:05 AM, 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.
>
> This is a special case of in-place filtering.
>
>> Suppose we have list 'arr':
>>
>>     arr = [1, 2, 3, 1]
>>
>>
>> and we want to remove all 1 from this list.
>>
>> The most Pythonic way to do it is:
>>
>>
>>     arr[:] = (x for x in arr if x != 1)
>
> arr[:] = filter(lambda x: x != 1, x)
>
>> 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
>>
>
> Python programmers really must learn either comprehensions or map and 
> filter.  They must also learn that repeatedly scanning a sequence 
> should be avoided when possible.
>
>> I was surprised that Python doesn't have easy way to remove all 
>> occurrences.
>
> The two ways above are pretty easy.
>
>> 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.
>>
>> This way looks a little bit nicer. I think so..
>>
>>     a.remove(1, all = True)
>
> I would not mind this, but I don't know if there are enough use cases 
> to justify an addition.
>

I am generally opposed to this.  This is sugar for filtering on a 
predicate, with the predicate simply being predefined as `bar == foo`.  
There are a number of other common filtering use cases, should we 
include them all?  Does this make python an easier language to use?

In the new user case, does this teach, or encourage the new user to 
intuit, how any other filtering operations should be written?  Would it 
not benefit the new user more to just have them learn listcomps, map, 
filter, and even while loops?


More information about the Python-ideas mailing list