4
$\begingroup$

Suppose I have a list as the following:

list={{1,9},{7,0},{8,6}....}

How can I reverse the element in such way that the output would be the following:

{{9,1},{0,7},{6,8}....}

I tried Map[Reverse,{list}] but it didn't work.

$\endgroup$
  • 1
    $\begingroup$ Either list[[All, {2,1}]], or more generally list[[All, Reverse[Range[Length[First[list]]]]]] $\endgroup$ – Coolwater Feb 3 '16 at 20:12
  • 3
    $\begingroup$ Take away the {}'s: Map[Reverse, list] or Reverse /@ map. $\endgroup$ – march Feb 3 '16 at 20:38
  • 3
    $\begingroup$ Closely related Why is multidimensional Reverse slow? $\endgroup$ – Kuba Feb 3 '16 at 20:45
9
$\begingroup$

Reverse takes a level specification so:

Reverse[list, 2]
$\endgroup$
0
$\begingroup$

Another approach would be to use a simple pattern match and replacement rule, such as:

list = {{1, 9}, {7, 0}, {8, 6}};
list /. {a_?NumberQ, b_?NumberQ} :> {b, a}
(*  {{9, 1}, {0, 7}, {6, 8}}. *)

For this specific example, you could drop the ?NumberQs from the pattern to be matched. But, without them, the approach would not produce the intended outcome if the length of the outer list were 2. For that case, the outcome would be as follows:

{{1, 9}, {7, 0}} /. {a_, b_} :> {b, a}
(*. {{7, 0}, {1, 9}}. *)
$\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.