Navdeep
Navdeep

Reputation: 863

Inserting same value at multiple indices of a List

I want to insert the same value at multiple indices in an empty list. For ex.

b=[1,3]
a=[0,0,0,0]
a[b]=10

I want to insert the value 10 at index 1 and 3 of a to get a=[0,10,0,10]. What is the simplest way to do it?

Upvotes: 1

Views: 3482

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

well, just a regular for loop:

b=[1,3]
a=[0,0,0,0]

for i in b:
    a[i]=10

print(a)

Output:

[0, 10, 0, 10]

but, if you use numpy, then you can in 1-line with advanced assignment:

import numpy as np

b = [1, 3]
a = np.array([0, 0, 0, 0])

a[b] = 10

print(a)

Upvotes: 4

Related Questions