Elisp: Modify List

By Xah Lee. Date: . Last updated: .

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

Push, Pop

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

(push 2 xx)
;; (2 1)

 xx
;; (2 1)
;; var is modified

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

;; nested list
(setq xx '((1 2) (3 4) (5 6)))

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

;; xx is modified
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
(push "b" (aref xx 1))
;; ("b" 3 4)

;; xx is modified
xx
;; [(1 2) ("b" 3 4) (5 6)]
pop
(pop listVar)

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

(setq xx (list 2 3 4))

(pop xx)
;; 2

xx
;; (3 4)

Replace Head, Replace Tail

setcar
(setcar listVar new)

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

(setq xx (list 1 2 3 4))

(setcar xx "a")
;; "a"

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 (list 1 2 3 4))

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

xx
;; (1 "a")

Add Element

add-to-list
(add-to-list listVar ELEMENT &optional APPEND COMPARE-FN)

Add to list when not already in it.

(setq xx (list 1 2 3))

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

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.

Drop Last N Items

nbutlast
(nbutlast listVar n)

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

(setq xx (list 0 1 2 3))

(nbutlast xx 1)
;; (0 1 2)

xx
;; (0 1 2)

Reference

Elisp, list

Special Lists

List Structure