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