# Using patterns in ReplaceAll to extract elements from tuples at arbitrary depths

I need to extract from MyList all last parts of each 3-tuple.

MyList={
{{0., 2, 5}},
{{0., 1, 8},{10., 10, 10},{10., 6, 2.5}},
{{0., 1.25, 10},{0., 8.9, 100}}
};


I tried to apply the following but it did not work:

MyList /. {a_Number, b_Number, c_Number} :> c


Please note, that a,b and c must be of Number, otherwise the last 3-tuple of MyList[[2]] would be extracted to, since it MyList[[2]] itself represents a 3-tuple.

The result must be:

{{5},{8,10,2.5},{10,100}}

-
did you mean to write list (with a lower case l)? – R. M. Aug 14 '12 at 4:16
@R.M: Thanks for the comment. Please see edit. – John Aug 14 '12 at 4:19
Also, there's no type Number. Consider _?NumberQ – Rojo Aug 14 '12 at 4:19
Indeed, integers have head Integer, reals have Real, rationals have Rational and complex numbers have Complex as head. So, no Number. – Sjoerd C. de Vries Aug 14 '12 at 7:33

Any time you write a pattern, you should stop and ask yourself a couple of questions — "Is this really a Head?", "Does this pattern test return True or False"... Number, which represents a real/integer in Read is different from ?NumericQ, which is a pattern test. In this case, the latter is what you need.

MyList /. {__, x_?NumericQ} :> x
(* {{5}, {8, 10, 2.5}, {10, 100}} *)


Alternately, you could also map Last to the appropriate level in your list:

Map[Last, MyList, {Depth[list] - 2}]
(* {{5}, {8, 10, 2.5}, {10, 100}} *)

-
+1 for teaching how to fish – Rojo Aug 14 '12 at 4:30
MyList /. {_, _, c_?NumberQ} :> c


{{5}, {8, 10, 2.5}, {10, 100}}

-