Elisp: List, Get Elements

By Xah Lee. Date: . Last updated: .

The following are basic functions to get elements from a list.

Get Nth Item

nth
(nth n list)

nth element. (Index starts from 0.)

(nth 0 (list 2 3 4))
;; 2

Get Head, Get Tail

car
(car list)

first element

(car (list 0 1 2 3))
;; 0
cdr
(cdr list)

rest elements

(cdr (list 0 1 2 3 4))
;; (1 2 3 4)

Get Nth Tail

nthcdr
(nthcdr n list)

rest starting at n.

(nthcdr 2 (list 0 1 2 3 4))
;; (2 3 4)

Take First N Items

take

(take N LIST)

  • Return the first N elements.
  • If N is zero or negative, return nil.
  • If N is greater or equal to the length of LIST, return a copy of LIST.
(let (xx yy)
  (setq xx (list 0 1 2 3))
  (setq yy (take 2 xx)))
;; (0 1)

;; if taking equal or more than list length, return is a copy
(let (xx yy)
  (setq xx (list 0 1 2 3))
  (setq yy (take 4 xx))
  ;; (0 1 2 3)
  (eq xx yy))
;; nil

Drop Last N Items

butlast
(butlast list n)

drop the last n elements.

(butlast (list 0 1 2 3) 1)
;; (0 1 2)

(butlast (list 0 1 2 3) 2)
;; (0 1)

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

;; normally, the return value is a new list

(setq xxa (list 0 1 2 3))
;; (0 1 2 3)

(setq xxb (butlast xxa 1))
;; (0 1 2)

(eq xxa xxb)
;; nil

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

;; if drop 0, return the same list

(setq xxa (list 0 1 2 3))

(setq xxb (butlast xxa 0))
;; (0 1 2 3)

(eq xxa xxb)
;; t

Last N items

last
(last list &optional n)
  • last n items. default is 1.
  • return a list

🛑 WARNING: when n is 1, it still return a list. To get the actual last item, use car on result.

(last (list 0 1 2 3 4) 2)
;; (3 4)
;; get the actual last item
(car (last (list 3 4 5)))
;; 5

Reference

Emacs Lisp, list

Special Lists

List Structure