How to reverse every other sublist of a list?
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
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}} *)