Search code examples
pythonlistreplacein-place

In-place replacement of all occurrences of an element in a list in python


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)?


Solution

  • We can iterate over the list with enumerate and replace the old value with new value, like this

    myl = [1, 2, 3, 4, 5, 4, 4, 4, 6]
    for idx, item in enumerate(myl):
        if item == 4:
            myl[idx] = 44
    print myl
    # [1, 2, 3, 44, 5, 44, 44, 44, 6]