Finding and replacing elements in a list Finding and replacing elements in a list python python

Finding and replacing elements in a list


Try using a list comprehension and a conditional expression.

>>> a=[1,2,3,1,3,2,1,1]>>> [4 if x==1 else x for x in a][4, 2, 3, 4, 3, 2, 4, 4]


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


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]replacements = {1:10, 2:20, 3:'foo'}replacer = replacements.get  # For faster gets.print([replacer(n, n) for n in a])> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]

Note that this approach works only if the elements to be replaced are hashable. This is because dict keys are required to be hashable.