Adding to the end of list in LISP

append, common-lisp, lisp

Solution

Either `push` to `last`, or use `nconc`:

> (defparameter a (list 1 2 3))
A
> (push 4 (cdr (last a)))
(4)
> a
(1 2 3 4)
> (nconc a (list 5))
(1 2 3 4 5)
> a
(1 2 3 4 5)

note that these are destructive operators, i.e., they modify the object which is the value of `a`, not just the binding of `a`.

This is why, BTW, you should never use `nconc` on quoted lists, like `(nconc '(1 2 3) '(4 5 6))`.

PS. Note that adding to the end of a list requires its full traversal and is thus an `O(length(list))` operation. This may be a bad idea if your lists are long, so people often use the `push`/`nreverse` idiom, e.g.,

(let (range)
  (dotimes (i 10 (nreverse range))
    (push i range)))
==> (0 1 2 3 4 5 6 7 8 9)

Problem

Possible Duplicate: what is the ‘cons’ to add an item to the end of the list? After watching many tutorials on lisp and searching high and low on google for answers, I still cannot figure out how to add to the end of a list in LISP. I want my function to add `'a` at the end of the list `'(b c d)` but I only know how to add it in front. Can someone help me use cons correctly to add `'a` at the end of the list? Here is my code. Thanks in advance. ``` (defun AddRt (a list) (cond ((null list) 0) (t (princ (cons a (cons (car list) (cdr list)))) ))) (AddRt 'a '(b c d)) ```

Original source

Related problems