Reputation: 126
I have a list called a
.
I have a list of indices called b
.
How do I set all the elements of a
with indices in b
to 0 ?
In other languages I could do a[b] = 0
, this returns the error TypeError: list indices must be integers or slices, not list
, I am not sure what the efficient pythonic way of accomplishing this is.
Both a
and b
may be fairly large.
#we are given this:
a = [2,4,6,8,10,12,14,16,18,20]#some list
b = [2,3,6,9]#some set of indices
#we aim to get this:
c = [6,8,14,20]
Edit to provide a sample code.
Upvotes: 2
Views: 65
Reputation: 126
I am answering this question based on some of the comments, as it was at the time locked due to me being unclear and not providing an example.
We can get c
as required by either using list comprehension :
#Solution 1, use list comprehension
c = [a[i] for i in b]
print(c)
or numpy:
#Solution 2, convert to numpy
a = np.array(a)
c = a[b]
print(c.tolist())
Upvotes: 2