Sometimes, we want to find and replace elements in a list with Python.
In this article, we’ll look at how to find and replace elements in a list with Python.
How to find and replace elements in a list with Python?
To find and replace elements in a list with Python, we can use list comprehension.
For instance, we write:
a = [1, 2, 3, 1, 3, 2, 1, 1]
b = [100 if x == 1 else x for x in a]
print(b)
We have list a
and we want to replace all the 1’s with 100.
To do this, we write [100 if x == 1 else x for x in a]
.
We check if x
is 1 where x
is each entry in a
.
We put 100 in the returned array if x
is 1. Otherwise, we put x
in the array.
Then we assign the returned array to b
.
Therefore b
is [100, 2, 3, 100, 3, 2, 100, 100]
.
Conclusion
To find and replace elements in a list with Python, we can use list comprehension.