Search code examples
pythonlistlist-comprehension

Substitute values in a list at multiple indices


Suppose I have the list:

mylist = [0] * 46

I want to set mylist[i] = 1, for each index in the list

indices_list = [0, 30, 40, 41]

Right now, I'm using a simple and readable for loop, since in Python you cannot use a list of indices as indices in a list (i.e., mylist[indices_list] = 1 is not valid Python code):

for i in indices_list:
    mylist[i] = 1

and it works nicely. However, I've been told that it would be better to use a list comprehension. Is this true? If so, how would I do it, and what would be the advantage with respect to my simple for loop?


Solution

  • Nah, it is not better. A list comprehension always creates a new list object. That means it has to process every element of the 46! A simple loop over the list of only 4 indices is just fine!