# How can I apply a function only to even-index elements of a list?

A = {1, 2, 3, 4, 5} and, Dd[P_] := P + 1

How can I map "Dd" into "A" such that the outcome is: {1, 3, 3, 5, 5}?

(Dd is only applied to the elements that its indexes are even)

• Welcome to the community. D is a built-in Mathematica function. It's recommended to not use single letter with upper case function names. Try MapAt[# + 1 &, {1, 2, 3, 4, 5}, 2 ;; ;; 2] Apr 30, 2022 at 15:32
• Thank you so much! :)
– Ito
Apr 30, 2022 at 15:38

I changed D to Dd:

MapAt[Dd, A, 2 ;; ;; 2]

• Thank you so much! But just to see if I got all of it, the "2 ;; ;; 2" thing translates exacly to: "All even indexes"?
– Ito
Apr 30, 2022 at 15:48
• @MatheusMantovaniMeneghel lookup Span in docs.
– Kuba
Apr 30, 2022 at 15:52

You can use the new ApplyTo:

A = {1, 2, 3, 4, 5};
Dd[P_] := P + 1

A[[2 ;; ;; 2]] //= Dd;
A
(*    {1, 3, 3, 5, 5}    *)

alist = {1, 2, 3, 4, 5}


Using MapIndexed:

MapIndexed[If[EvenQ @@ #2, #1 + 1, #] &, alist]


Generate {0,1,0,1..} array

blist = (Flatten@ConstantArray[{0, 1}, Ceiling[Length@alist/2]])[[1 ;;
Length@alist]]


{0, 1, 0, 1, 0}

alist + blist


Using ReplacePart:

evenrange = Range[2, Length@alist, 2];

ReplacePart[alist, Thread[evenrange -> alist[[evenrange]] + 1]]


Result:

{1, 3, 3, 5, 5}


Using Position and Map:

Map[If[EvenQ[Det[Position[A, #]]] === True, # + 1, #] &, A]
(*{1, 3, 3, 5, 5}*)


Using Outer, Range and MapAt:

MapAt[# + 1 &, A, Outer[List, Range[2, Length[A], 2]]]
(*{1, 3, 3, 5, 5}*)


Using Position and Map:

Plus[Map[If[EvenQ[Det[Position[A, #]]] === True, 1, 0] &, A], A]
(*{1, 3, 3, 5, 5}*)

• A very nice use of Det, too May 2, 2022 at 8:37
SubsetMap[dd, arr, 2 ;; -1 ;; 2]

(* {1, 3, 3, 5, 5} *)


where:

arr = {1, 2, 3, 4, 5};
dd[p_] := p + 1


Just for fun

{arr[[1;;-1;;2]], dd@arr[[2;;-1;;2]]} // Flatten[#, {{2,1}}]&

(* {1, 3, 3, 5, 5} *)

MapIndexed[#1+Boole@EvenQ[#2][[1]]&, arr]

(* {1, 3, 3, 5, 5} *)

• To transpose a 'ragged' array with Flatten, see this answer by Leonid Shifrin May 1, 2022 at 9:26