Assume I have a list:
myl = [1, 2, 3, 4, 5, 4, 4, 4, 6]
What is the most efficient and simplest pythonic way of in-place (double emphasis) replacement of all occurrences of 4
with 44
?
I'm also curious as to why there isn't a standard
way of doing this (especially, when strings
have a not-in-place replace
method)?
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
myl[:] = [x if x != 4 else 44 for x in myl]
Perform the replacement not-in-place with a list comprehension, then slice-assign the new values into the original list if you really want to change the original.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With