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

Eduard Bondarenko bondarenkoedik at gmail.com
Sat Oct 3 17:05:26 CEST 2015


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.

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)


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


I was surprised that Python doesn't have easy way to remove all occurrences.
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)


So, that's idea in brief.
Bellow you can find description how to install and test patch.
Patch is attached.

Note: this is test patch, so some things may not be done in accordance with
PEP 007.

How to install patch:

hg update 3.5

cd Objects

patch < remove_all.patch

make

How to use patch:


>>> arr = [1, 2, 3, 1]

>>> arr.remove(1)

>>> arr

[2, 3, 1]

>>> arr = [1, 2, 3, 1]

>>> arr.remove(1, all = True)

>>> arr

[2, 3]


>>> arr = [1, 2, 3, 1]

>>> arr.remove(1, True)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: remove() takes one argument


>>> arr.remove(1, al = True)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'al' is an invalid keyword argument for this function



Many thanks for your attention!
- Eduard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151003/8cce30b8/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: remove_all.patch
Type: application/octet-stream
Size: 2176 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151003/8cce30b8/attachment.obj>


More information about the Python-ideas mailing list