[Python-ideas] Proposal how to remove all occurrences of a value from a Python list
Rob Cliffe
rob.cliffe at btinternet.com
Sun Oct 4 01:14:15 CEST 2015
On 03/10/2015 22: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)
I think you mean
arr[:] = filter(lambda x: x!=1, arr)
which suggests that using filter/map is not quite as easy as its
advocates believe. :-)
>
>>
>> This way looks a little bit nicer. I think so..
>>
>> a.remove(1, all = True)
>
Other things that might be useful (sorry, I have no use cases in mind):
a.remove(1, count) # maximum number of removals, analogous to
aString.replace(old, new, count)
a remove-like function that does not raise an error if the item is
not present
a remove-like function that returns the mutated list (like
sorted(), as opposed to list.sort() )
It's not obvious to me how to design good API(s) to do some/all of this.
Rob Cliffe
More information about the Python-ideas
mailing list