10
$\begingroup$

Suppose I have a list

{a, b, c, d} 

I want to operate on this list with a function which depends on the index of the element, e.g. I want to add the index number to each element to get

{a+1, b+2, c+3, d+4}

what would be the best way to do this?

I have seen some possible approaches but was wondering what the 'canonical' way would be.

$\endgroup$

3 Answers 3

14
$\begingroup$

MapIndexed:

MapIndexed[#2[[1]] + # &, {a, b, c, d}]

{1 + a, 2 + b, 3 + c, 4 + d}

Also

Range[Length @ #] + # & @ {a,b,c,d}

{1 + a, 2 + b, 3 + c, 4 + d}

$\endgroup$
5
$\begingroup$

A couple more options --

lst = {a, b, c, d};

Table[lst[[n]] + n, {n, Length[lst]}]

{1 + a, 2 + b, 3 + c, 4 + d}

lst + Range[Length[lst]]

{1 + a, 2 + b, 3 + c, 4 + d}

$\endgroup$
2
$\begingroup$

Four more possibilities:

list = {a, b, c, d};

Array[{list[[#]] + #} &, Length @ list]

{{1 + a}, {2 + b}, {3 + c}, {4 + d}}

Module[{i = 1}, # + i++ &] /@ list

{1 + a, 2 + b, 3 + c, 4 + d}

ReplacePart[i_ :> list[[i]] + i] @ list

{1 + a, 2 + b, 3 + c, 4 + d}

Module[{i = 1}, Replace[list, x_ :> x + i++, {1}]]

{1 + a, 2 + b, 3 + c, 4 + d}

Replace can be useful if we want to impose a Condition:

list = {1, 2, 3, Missing[], 4};

Module[{i = 1}, Replace[list, x_Integer :> x + i++, {1}]]

{2, 4, 6, Missing[], 8}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.