Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 519
lifebalance Avatar asked Jun 13 '14 09:06

lifebalance


People also ask

How do you replace all occurrences in a list in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you remove all occurrences of an element in a list in Python?

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.

How do you replace multiple elements in a list in Python?

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.


1 Answers

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.

like image 183
user2357112 supports Monica Avatar answered Sep 21 '22 20:09

user2357112 supports Monica