Python Enhancement Proposal for List methods

Lutz Horn lutz.horn at posteo.de
Mon Oct 22 05:29:59 EDT 2018


On Sun, Oct 21, 2018 at 06:06:40PM +0530, Siva Sukumar Reddy wrote:
> 1. *list.replace( item_to_be_replaced, new_item )*: which replaces all the
> occurrences of an element in the list instead of writing a new list
> comprehension in place.

Try this:

>>> l = [1, 3, 4, 5, 6, 5, 4, 3, 2, 1]
>>> def replace(l, old, new):
...     try:
...         while True:
...             l[l.index(old)] = new
...     except ValueError:
...         pass
...     
... 
>>> replace(l, 5, 55)
>>> l
[1, 3, 4, 55, 6, 55, 4, 3, 2, 1]

Functions like this are simple to implement. There is no need to add
them to the stdlib.

Lutz



More information about the Python-list mailing list