As a Mathematica beginner reading through Paul Wellin’s Mathematica book, I ran across a very interesting example
{{3, 4}, {7, 2}, {1, 5}} /. {x_, y_} :> {y, x}
which returns the elements of each ordered pair exchanged resulting in {{4, 3}, {2, 7}, {5, 1}}
I thought it would be interesting to generalize it for handling “rows” with two or more columns without regard to how many columns each row had (or the number of rows in the list) and using a rule something like
{x_, y_, z___} :>{y, x, z}
But, I quickly ran into a problem which has caused me to realize I do not understand what Mathematica is going to do in general. Not only did my rule not work, it failed in a way not predictable to me. Simplifying problem with Wellin’s example modified to be a 2 x 2 matrix instead of a 3 x 2 matrix:
{{3, 4}, {7, 2}} /. {x_, y_} :> {y, x}
results in {{7, 2}, {3, 4}}
That is, Mathematica no longer exchanges the elements within each sublist, it exchanges the sublists. This is confusing to me because I expected if a rule works with a simplified sample problem it will work with generalized versions. That seems not to be the case.
Why is Mathematica doing this and how should be expression be coded to work as I had expected?