Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing particular elements in a list

Tags:

python

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?

like image 521
bdhar Avatar asked Sep 30 '11 10:09

bdhar


People also ask

How do you replace multiple elements in a list in Python?

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.

How do you replace an element in a specific index in a list?

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 .

How do you use replace in a list?

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 .


2 Answers

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]
like image 109
Mark Byers Avatar answered Sep 23 '22 02:09

Mark Byers


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

['XXX' if item == 'abc' else item for item in mylist]
like image 39
agf Avatar answered Sep 22 '22 02:09

agf