## Get last element of a list

Discussion of Common Lisp

### Get last element of a list

Hi Guys! help please..How can i get the last element of a list with a list? say i have a list
Code: Select all
`((4 5 6) (d e f) (h i j) (5 5 5 5)) )`

how can i have the last element so that my out put would be
(6 f j 5)

daimous

### Re: Get last element of a list

Treasure hunt: You can use two functions from the following lists.
(apropos "last" :cl)
(apropos "map" :cl)

More details can be found in the HyperSpec. A good search tool is at
http://lispdoc.com/

Or see the quick reference at
http://clqr.berlios.de/

nuntius

Posts: 532
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

### Re: Get last element of a list

@daimous

You need to use mapcar in combination wiht the lambda-function. it's the best way to solve your problem!

Code: Select all
`(defun getAllLastElems(listOfLists)     (mapcar (lambda (list-elem)                        (last list-elem)                  ) listOfLists))`

just try it. I don't know if the function (last list) is correct. If it isn't, try to found a function that return you the last
element of a simple list and replace it with the function last in this code (with the same argument. Don't change the name [list-elem]!)
Wolfgang Tsafack

Posts: 12
Joined: Thu Nov 05, 2009 11:09 am

### Re: Get last element of a list

or simply
Code: Select all
`(mapcan #'last '((4 5 6) (d e f) (h i j) (5 5 5 5)))`

nuntius

Posts: 532
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

### Re: Get last element of a list

Code: Select all
`(defun mylast(x)       (if (and (listp x) (null (cdr x)) ) (car x)       (mylast (cdr x))))(defun eachlast(x)        (if (null x) x       (progn              (cons (mylast (car x))              (eachlast (cdr x))))))`

CL-USER> (eachlast '((1 9 5)(3 3 3)(1 0 3 0 2)))
(5 3 2)
methusala

Posts: 35
Joined: Fri Oct 03, 2008 6:35 pm

### Re: Get last element of a list

(defun getAllLastElems(listOfLists)
(mapcar (lambda (list-elem)
(last list-elem)
) listOfLists)
)

Hello, I make an error when writing this last post. The function last return a list not a value
Code: Select all
`(last '(a d 6)) --> (6)`

So you have to add first/or car into the lambda-function. So the correct code is show below:

(defun getAllLastElems(listOfLists)
(mapcar (lambda (list-elem)
(car (last list-elem))
) listOfLists)
)

That work effiziently.

@methusala
That was also a good idea solving the problem. But too long for me.

all have a good day
Wolfgang Tsafack

Posts: 12
Joined: Thu Nov 05, 2009 11:09 am