6
$\begingroup$

I couldn't find a similar question so I decided to ask this one. I have a nested list with many sublists of equal length. To make things easier let's say it's like that:

list={{2,1,7},{3,9,5},{4,8,6}}

I'd like to get a list of last elements from each sublist, in this case:

{7,5,6}

I'm not sure whether i should think of a pattern to do this or is there a simpler way?

$\endgroup$
4
  • 2
    $\begingroup$ Here are a few options: 1. Last /@ list 2. list[[All, -1]] 3. list /. {___, i_Integer} :> i $\endgroup$
    – rm -rf
    Jan 27, 2014 at 16:53
  • 1
    $\begingroup$ list[[;; , -1]] $\endgroup$
    – RunnyKine
    Jan 27, 2014 at 16:55
  • 1
    $\begingroup$ Transpose[list][[-1]] $\endgroup$
    – C. E.
    Jan 27, 2014 at 16:55
  • $\begingroup$ That was fast - thanks guys! $\endgroup$
    – Wojciech
    Jan 27, 2014 at 17:01

1 Answer 1

9
$\begingroup$

It is

list = {{2, 1, 7}, {3, 9, 5}, {4, 8, 6}};
list[[All, -1]]
(* {7, 5, 6} *)

or

Last /@ list
(* {7, 5, 6} *)
$\endgroup$
3
  • 3
    $\begingroup$ For beginners, the latter command is shorthand for Map[Last[#]&,list] $\endgroup$ Jan 27, 2014 at 17:10
  • 2
    $\begingroup$ Actually Map[Last, list] $\endgroup$
    – Rojo
    Jan 27, 2014 at 19:39
  • $\begingroup$ @Rojo Hehe... :-) $\endgroup$
    – halirutan
    Jan 27, 2014 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.