# How to reverse every other sublist of a list?

I have a list with sublists list = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}. I would like to reverse every other sublist, starting from the second one. The result would look like result = {{1, 2}, {4, 3}, {5, 6}, {8, 7}}. What would be a simple way to do this?

Use MapAt, which accepts the same syntax as Part:

MapAt[Reverse, list, {2 ;; ;; 2}]
(* {{1, 2}, {4, 3}, {5, 6}, {8, 7}} *)


Using Part and Span might not seem overly elegant but it is fast:

list = RandomReal[{-1, 1}, {100000, 10}];

a = MapAt[Reverse, list, {2 ;; ;; 2}]; // RepeatedTiming // First

b = ReplacePart[list, i_?EvenQ :> Reverse@list[[i]]]; // RepeatedTiming // First

c = Module[{result = list},
result[[2 ;; ;; 2]] = list[[2 ;; ;; 2, -1 ;; 1 ;; -1]];
result
]; // RepeatedTiming // First

a == b == c


0.11

0.317

0.0036

True

• A bit cleaner, s/b comparable in speed: Riffle[list[[;; ;; 2]], list[[2 ;; ;; 2, -1 ;; 1 ;; -1]]] – ciao Apr 10 '19 at 21:00

Another method is to use ReplacePart:

ReplacePart[{{1, 2}, {3, 4}, {5, 6}, {7, 8}},
i_ ? EvenQ :> Reverse@list[[i]]
]
(* {{1,2},{4,3},{5,6},{8,7}} *)


This will work

list = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};

Table[If[EvenQ[i], Reverse[list[[i]]], list[[i]]], {i, 1, Length[list]}]

(*{{1, 2}, {4, 3}, {5, 6}, {8, 7}}*)
$$$$
`