> If I want to do this then I can do, for example: > > (prog1 (car (last mylist)) (setq mylist (nbutlast mylist))) > > But here last and nbutlast walks the list twice unnecessarily. > > Shouldn't emacs provide a function which does it in one step, so the > list isn't walked twice? > > E.g. (choplast mylist) > > which returns a cons cell of (LAST . CHOPPEDLIST) > > Of course, returning two values is not very lispy, but at least it > could be more efficient. > > Is there an existing function which does this in one step? If not, > shouldn't there be one built-in emacs, for efficient manipulation of > the list's end? Here. It returns the last element, and it chops that last element off the list. (You don't need to also return the updated list, since you already have it as the arg. But if you want to return it then return a cons, as you did.) (defun choplast (xs) (let ((m (length xs))) (and (< 1 m) (let ((cons (nthcdr (- m 2) xs))) (prog1 (cadr cons) (setcdr cons nil)))))) (setq foo '(1 2 3 4 5 6 7 8 9)) (choplast foo) ; -> 9 ; foo = (1 2 3 4 5 6 7 8) (setq foo '(1 2)) (choplast foo) ; -> 2 ; foo = (1) (setq foo '(1)) (choplast foo) ; -> nil ; foo = (1)