Home > Software design >  How to set the same value in multiple index of array once python?
How to set the same value in multiple index of array once python?

Time:12-06

I have array like this: a=[1,2,3,4,5,6,7]

i need to replace the value of the index 1 , 4 ,5 by the value 10 but without using for loop.

the result: a=[1,10,3,4,10,10,7]

CodePudding user response:

I guess you could utilize numpy for this:

import numpy as np
    
a = np.array([1, 2, 3, 4, 5, 6, 7])
    
indices = [1, 4, 5]
        
a.put(indices, 10)

result:

array([ 1, 10,  3,  4, 10, 10,  7])

CodePudding user response:

Is this okay?

a[1] = a[4] = a[5] = 10

CodePudding user response:

You can use numpy to do this.

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7])
toChange = [1, 4, 5]
a[toChange] = 10 # changes all indices in toChange into 10

You may even pass a list to change each selected index into a different value using:

a[toChange] = [0, 1, 10]
  • Related