5
$\begingroup$

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?

$\endgroup$
13
$\begingroup$

Use MapAt, which accepts the same syntax as Part:

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

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

$\endgroup$
  • 2
    $\begingroup$ A bit cleaner, s/b comparable in speed: Riffle[list[[;; ;; 2]], list[[2 ;; ;; 2, -1 ;; 1 ;; -1]]] $\endgroup$ – ciao Apr 10 at 21:00
4
$\begingroup$

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}} *)
$\endgroup$
3
$\begingroup$

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}}*)
```
$\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.