Python Enhancement Proposal for List methods

Peter Otten __peter__ at web.de
Mon Oct 22 05:44:19 EDT 2018


Siva Sukumar Reddy wrote:
> I am really new to Python contribution community want to propose below
> methods for List object. Forgive me if this is not the format to send an
> email.
>> 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.
> 2. *list.replace( item_to_be_replaced, new_item, number_of_occurrences )*:
> which replaces the occurrences of an element in the list till specific
> number of occurrences of that element. The number_of_occurrences can
> defaulted to 0 which will replace all the occurrences in place.
> 3. *list.removeall( item_to_be_removed )*: which removes all the
> occurrences of an element in a list in place.
>> What do you think about these features?
> Are they PEP-able? Did anyone tried to implement these features before?
> Please let me know.

You can easily implement those as functions.
def list_replace(items, old, new, count=None):
 indices = (i for i, v in enumerate(items) if v == old)
 if count is not None:
 indices = itertools.islice(indices, count)
 for index in indices:
 items[index] = new
def list_removeall(items, value):
 for index in reversed(range(len(items))):
 if items[index] == value:
 del items[index]
To promote them to methods of a built-in class you need to provide use-cases
that are both frequent and compelling, I think.
So what are your use-cases?


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /