If you want to always replace at second level only, you can use
Replace[{{3, 4}, {7, 2}, {1, 5}}, {x_, y_} :> {y, x}, {2}]
(* {{4, 3}, {2, 7}, {5, 1}} *)
Replace[{{3, 4}, {7, 2}}, {x_, y_} :> {y, x}, {2}]
(* {{4, 3}, {2, 7}} *)
The reason why ReplaceAll[{{3, 4}, {7, 2}}, {x_, y_} :> {y, x}]
produced {{7, 2}, {3, 4}}
and not {{4, 3}, {2, 7}}
is because Mathematica matched {x_,y_}
with {3, 4}, {7, 2}
as a whole, hence x_
matched {3, 4}
and y_
matched {7, 2}
and so it returned these flipped (ReplaceAll stops once it finds a match and starts from first level). In the first case ReplaceAll[{{3, 4}, {7, 2}, {1, 5}}, {x_, y_} :> {y, x}]
it worked, since Mathematica tried first to match at first level, and could not (not possible to match {a,b,c}
with {x_,y_}
, so it went to second level, and found the pattern it can match to, and hence it worked then.
So if you want to always match at specific level, you can use Replace
with specific level and be explicit about it. Look up help for Replace
. It makes a difference if ones uses level {n}
vs. n
also. {n}
says only level n
, while n
means level 1 to n
.