Skip to main content

assignment - Setting parts of a list



Suppose I have list


a = Range[10]


{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}



in which I want to set some elements to be a list


a[[4 ;; 7]] = {1, 2, 3}; 



{1, 2, 3, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, 8, 9, 10}



Which is fine and dandy unless my part span is the same length as my list:


a[[4 ;; 6]] = {1, 2, 3};


{1, 2, 3, 1, 2, 3, 7, 8, 9, 10}



How can I force the assignment to behave consistently? In my case, I always want the first behaviour. But conceivably someone might always want the second behaviour with errors if the lengths don't match.



Answer




(a[[#]] = {1, 2, 3}) & /@ Range[4, 6];

You get:


In[1]:= a

Out[1]= {1, 2, 3, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, 7, 8, 9, 10}

A convenient thing to remember is that if your elements are not sequential it is still easy to set up:


(a[[#]] = {1, 2, 3}) & /@ {1, 3, 10};


In[2]:= a

Out[2]= {{1, 2, 3}, 2, {1, 2, 3}, 4, 5, 6, 7, 8, 9, {1, 2, 3}}

Comments