Elisp: Modify List

By Xah Lee. Date: . Last updated: .

The following are basic functions for modifying 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

;; HHHH------------------------------

;; arg must be a variable.
;; this is error
(push 2 (list 0 1 2))

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 99)
;; 99

xx
;; (99 2 3 4)

;; HHHH------------------------------

;; the first arg need not be a variable
;; (but then it's useless)
(setcar (list 2 3 4) 99)
;; 99
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 9 nil))
;; (9)

xx
;; (1 9)

;; HHHH------------------------------

;; the first arg need not be a variable.
;; (but then it's useless)
(setcdr (list 3 4 5) (cons 9 nil))
;; (9)

Add Element

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

Add to list when not already in it.

(setq xx (list 1 2 3))

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

xx
;; (9 1 2 3)
add-to-ordered-list
(add-to-ordered-list listVar item &optional ORDER)

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

Take First N Items (Modify Variable)

ntake

(ntake N listVar)

  • Take the first N elements.
  • The original list is modified
  • If N is zero or negative, return nil.
  • If N is greater or equal to the length of LIST, return LIST unmodified.
(ntake 2 (list 3 4 5))
;; (3 4)

;; HHHH------------------------------

(setq xx (list 3 4 5))

(ntake 2 xx)
;; (3 4)

;; the variable is modified
xx
;; (3 4)

Drop Last N Items (Modify Variable)

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

Emacs Lisp, list

Special Lists

List Structure