Skip to main content

map - Using MapIndexed only at certain elements of a list



MapIndexed is a very handy built-in function. Suppose that I have the following list, called list:


list = {10, 20, 30, 40};

I can use MapIndexed to map an arbitrary function f across list:


{f[10, {1}], f[20, {2}], f[30, {3}], f[40, {4}]}

where the second argument to f is the part specification of each element of the list.


But, now, what if I would like to use MapIndexed only at certain elements? Suppose, for example, that I want to apply MapIndexed to only the second and third elements of list, obtaining the following:


{10, f[20, {2}], f[30, {3}], 40}


Unfortunately, there is no built-in "MapAtIndexed", as far as I can tell. What is a simple way to accomplish this? Thanks for your time.



Answer



If does the job and is simple enough:


MapIndexed[If[2 ≤ First@#2 ≤ 3, f[#, #2], #] &, list]
(* {10, f[20, {2}], f[30, {3}], 40} *)

Comments