Home » Python » finding and replacing elements in a list (python)

finding and replacing elements in a list (python)

Posted by: admin November 1, 2017 Leave a comment

Questions:

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.

Answers:
>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> for n,i in enumerate(a):
...   if i==1:
...      a[n]=10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

Questions:
Answers:

Try using a list comprehension and the ternary operator.

>>> 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]

Questions:
Answers:

List comprehension works well–and looping through with enumerate can save you some memory (b/c the operation’s essentially be doing in place).

There’s also functional programming…see usage of map:

    >>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
    >>> map(lambda x:x if x!= 4 else 'sss',a)
    [1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]

Questions:
Answers:
>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
...     a[i] = replacement_value
... 
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>> 

Questions:
Answers:

If you have several values to replace, you can also use a dictionary:

a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}

print([dic[n] if n in dic else n for n in a])

> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]

Questions:
Answers:

The following is a very direct method in Python 2.x

 a = [1,2,3,4,5,1,2,3,4,5,1]        #Replacing every 1 with 10
 for i in xrange(len(a)):
   if a[i] == 1:
     a[i] = 10  
 print a

This method works. Comments are welcome. Hope it helps 🙂

Also try understanding how outis’s and damzam’s solutions work. List compressions and lambda function are useful tools.