bdhar
bdhar

Reputation: 22973

Replacing particular elements in a list

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?

Upvotes: 7

Views: 288

Answers (2)

Mark Byers
Mark Byers

Reputation: 838056

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]

Upvotes: 14

agf
agf

Reputation: 176750

Use a list comprehension with a ternary operation / conditional expression:

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

Upvotes: 11

Related Questions