[Python-ideas] Proposal how to remove all occurrences of a value from a Python list
Terry Reedy
tjreedy at udel.edu
Sat Oct 3 23:54:40 CEST 2015
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.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list