what's the typical way to add an item to the end of the list?
I have a list (1 2 3) and want to add 4 to it (where 4 is the result of an evaluation (+ 2 2))
(setf nlist '(1 2 3))
(append nlist (+ 2 2))
This says that append expects a list, not a number. How would I accomplish this?
Cons-ing at the end of a list can be achieved with this function:
You could use append, but beware that it can lead to bad performance if used in a loop or on very long lists.
If performance is important, the usual idiom is building lists by prepending (using cons), then reverse (or nreverse).
If you want to add an item onto the end of a given list without changing that list, then as previously suggested you can use a function like
This returns a new extended list, while preserving the input list. However, if you want to modify the input list to include the added item, then you can use a macro like
Pushend operates like push, but "pushes" the item onto the end of the given list. Also note the argument order is the reverse of push.
If you are trying to add two lists for example
(1 2 3) + (1 2 3)
here is the code (recursive)If you are trying to add an item to the end of the second list, for example
3 + (1 2 3)
(append l (list e)) ; e is the element that you want to add at the tail of a list
You haven't specified the kind of Lisp, so if you use Emacs Lisp and
dash
list manipulation library, it has a function-snoc
that returns a new list with the element added to the end. The name is reversed "cons".