## finding and replacing elements in a list

### Question

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.

2019/08/01
1
289
8/1/2019 5:23:04 PM

``````>>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for n, i in enumerate(a):
...   if i == 1:
...      a[n] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
``````
2018/01/31
261
1/31/2018 1:46:57 PM

If you have several values to replace, you can also use a dictionary:

``````a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}

print([dic.get(n, n) for n in a])

> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]
``````
2018/01/08

List comprehension works well, and looping through with enumerate can save you some memory (b/c the operation's essentially being done in place).

There's also functional programming. See usage of map:

``````>>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
>>> map(lambda x: x if x != 4 else 'sss', a)
[1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
``````
2019/01/17

``````>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
...     a[i] = replacement_value
...
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>>
``````
2010/04/06

``````a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
if a[i]==2:
a[i]=123
``````

You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1

2018/01/31

To replace easily all `1` with `10` in `a = [1,2,3,4,5,1,2,3,4,5,1]`one could use the following one-line lambda+map combination, and 'Look, Ma, no IFs or FORs!' :

`# This substitutes all '1' with '10' in list 'a' and places result in list 'c':`

`c = list(map(lambda b: b.replace("1","10"), a))`

2019/12/30