8
$\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$

2 Answers 2

11
$\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$
3
$\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$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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