ELisp: Modify List

By Xah Lee. Date: . Last updated: .

The following are basic functions for modify a list in-place.

Add Element

push
(push new listVar)
  • Add element to the front.
  • Modify the listVar.
  • Return the new value of listVar
(setq xx '(1))

;; after push, the var is modified, and the var's new value is returned
(eq (push 2 xx) xx)

(equal xx '(2 1))

The variable is modified even if the pushed list is inside a list.

;; a list of lists
(setq xx '((1 2) (3 4) (5 6)))

;; push b to one of the list
(equal
 (push "b" (nth 1 xx))
 '("b" 3 4))

;; the xx is modified
(equal
 xx
 '((1 2) ("b" 3 4) (5 6)))

also if the variable is a vector:

;; a vector of lists
(setq xx [(1 2) (3 4) (5 6)])

;; push b to one of the list
(equal
 (push "b" (aref xx 1))
 '("b" 3 4 ))

;; the xx is modified
(equal
 xx
 [(1 2) ("b" 3 4 ) (5 6)]
 )
add-to-list
(add-to-list listVar ELEMENT &optional APPEND COMPARE-FN)

Add to list when not already in it.

(setq xx '(1 2 3))

;; add "a" to it. return the modified var
(eq
 (add-to-list 'xx "a" )
 xx)

;; check the new value
(equal
 xx
 '("a" 1 2 3))
add-to-ordered-list
(add-to-ordered-list listVar ELEMENT &optional ORDER)

Add to specific position in list, if it does not exist. The list is reordered.

Remove Element

pop
(pop listVar)

Remove first element from the variable. Return the removed element.

(setq xx '(1 2 3 4))
(equal (pop xx) 1)
(equal xx '(2 3 4))
nbutlast
(nbutlast listVar n)

Remove last n elements from the variable. Return the new value of the variable.

(setq xx '(0 1 2 3))
(equal (nbutlast xx 1) '(0 1 2))
(equal xx '(0 1 2))

Replace Element

setcar
(setcar listVar new)

Replace the first element in listVar with new. Return new.

(setq xx '(1 2 3 4))
(equal (setcar xx "a") "a")
(equal xx '("a" 2 3 4))
setcdr
(setcdr listVar newTail)

Replace the rest of elements in listVar with newTail. Return newTail.

🛑 WARNING: if you want the result to be a Proper List, the newTail should be a proper list.

(setq xx '(1 2 3 4))

(equal
 (setcdr xx (cons "a" nil))
 (cons "a" nil))

(equal xx '(1 "a"))

Reference

Emacs Lisp List

Special Lists

List Structure