Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding and replacing elements in a list

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?

For example, suppose my list has the following integers

>>> a = [1,2,3,4,5,1,2,3,4,5,1] 

and I need to replace all occurrences of the number 1 with the value 10 so the output I need is

>>> a = [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10] 

Thus my goal is to replace all instances of the number 1 with the number 10.

like image 308
James Avatar asked Apr 06 '10 01:04

James


1 Answers

Try using a list comprehension and a conditional expression.

>>> a=[1,2,3,1,3,2,1,1] >>> [4 if x==1 else x for x in a] [4, 2, 3, 4, 3, 2, 4, 4] 
like image 129
outis Avatar answered Sep 17 '22 20:09

outis