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

lifebalance picture lifebalance · Jun 13, 2014 · Viewed 25.5k times · Source

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

Answer

user2357112 supports Monica picture user2357112 supports Monica · Jun 13, 2014
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.