Code:
>>> mylist = ['abc','def','ghi']
>>> mylist
['abc', 'def', 'ghi']
>>> for i,v in enumerate(mylist):
... if v=='abc':
... mylist[i] = 'XXX'
...
>>> mylist
['XXX', 'def', 'ghi']
>>>
Here, I try to replace all the occurrences of 'abc'
with 'XXX'
. Is there a shorter way to do this?
One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
You use simple indexing using the square bracket notation lst[i] = x to replace the element at index i in list lst with the new element x .
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
Instead of using an explicit for loop, you can use a list comprehension. This allows you to iterate over all the elements in the list and filter them or map them to a new value.
In this case you can use a conditional expression. It is similar to (v == 'abc') ? 'XXX' : v
in other languages.
Putting it together, you can use this code:
mylist = ['XXX' if v == 'abc' else v for v in mylist]
Use a list comprehension with a ternary operation / conditional expression:
['XXX' if item == 'abc' else item for item in mylist]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With