Finding and replacing elements in a list

list, python, replace

Solution

You can use the built-in `enumerate` to get both index and value while iterating the list. Then, use the value to test for a condition and the index to replace that value in the original list:

>>> a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for i, n in enumerate(a):
...   if n == 1:
...      a[i] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

Problem

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this? For example, suppose my list has the following integers ``` a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1] ``` and I need to replace all occurrences of the number 1 with the value 10 so the output I need is ``` a = [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10] ``` Thus my goal is to replace all instances of the number 1 with the number 10.

Original source