On Mon, Oct 22, 2018 at 11:20 PM Lutz Horn <lutz.h...@posteo.de> wrote: > > 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. >
And simple to get wrong, hence my recommendation for a recipe in the docs. For example, your replace() function will get into an infinite loop if old and new compare equal to each other. It's also going to start the search over from the beginning every time it finds something, which is wasteful. ChrisA -- https://mail.python.org/mailman/listinfo/python-list