[Python-ideas] Proposal how to remove all occurrences of a value from a Python list
Sven R. Kunze
srkunze at mail.de
Tue Oct 6 18:29:54 CEST 2015
On 06.10.2015 13:24, M.-A. Lemburg wrote:
> If you have more than a few values to remove, it's often
> faster to create a new list, since each removal will
> require a copy operation of all trailing items and (every
> now and then) a realloc of the list object to free
> up the unused space:
>
> new_arr = [x
> for x in arr
> if x != 1]
>
I think that's a technical detail which can be sorted out in C somehow
more efficiently.
But the proposal is not about performance rather than readability and
maintainability.
> On 05.10.2015 22:18, Terry Reedy wrote:
>> The problem with methods is that they only work with one class. A list.removeall would only remove
>> things equal to a specific item from a list (and presumably in place). We already have both a
>> generic filter function and syntax that will remove all items from any iterable that meet any
>> condition. The stream can be fed into any other function that accept an iterable.
remove also removes in-place but it's not overly useful when you know or
unsure about whether you need to remove an item multiple times.
remove_all would basically complement remove as a more generic alternative.
Btw. one could also think of an additional generalization for this that
basically takes n arguments which are then removed altogether from the
list in question:
a = [1,2,3,5,4,2,3,4,1,2]
a.remove_all(1,4,2)
a == [3,5,3]
Just thinking, and I might remember some time where I would have found
it useful. Not sure.
Best,
Sven
More information about the Python-ideas
mailing list