Replacing individual items in a list

the 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 am trying to replace all occurrences of 'abc' with 'XXX' . Is there a shorter way to do this?

+7
source share
2 answers

Instead of using an explicit for loop, you can use list comprehension . This allows you to iterate over all the items in the list and filter them or match them to the new value.

In this case, you can use a conditional expression . Does it look like (v == 'abc') ? 'XXX' : v (v == 'abc') ? 'XXX' : v in other languages.

Combining this, you can use this code:

 mylist = ['XXX' if v == 'abc' else v for v in mylist] 
+14
source

Use a triple operation list description / conditional expression :

 ['XXX' if item == 'abc' else item for item in mylist] 
+11
source

All Articles