Emacs Lisp: List, Get Elements

By Xah Lee. Date: . Last updated: .

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

First, Rest

car
(car list) first element
(equal
 (car '("a" "b" "c"))
 "a"
 )
cdr
(cdr list)

rest elements

(equal
 (cdr '(0 1 2 3 4))
 '(1 2 3 4))

Nth, Nth Rest, Not N Rest

nth
(nth n list)

nth element. (Index starts from 0.)

(equal
 (nth 1 '(0 1 2 3 4))
 1)
nthcdr
(nthcdr n list)

rest starting at n.

(equal
 (nthcdr 2 '(0 1 2 3 4))
 '(2 3 4))
butlast
(butlast list n)

without the last n elements.

(equal
 (butlast '(0 1 2 3 4 5))
 '(0 1 2 3 4))

(equal
 (butlast '(0 1 2 3 4 5) 2)
 '(0 1 2 3))

Last, Last N

last
(last list)

last as a list. i.e. return (cons lastElement nil).

To get the actual last item of a list, do (car (last list))

(equal
 (car (last (list "a" "b" "c")))
 "c"
 )

(equal
 (last (list "a" "b" "c"))
 (cons "c" nil)
 )
last
(last list &optional n)

last n items.

(equal
 (last '(0 1 2 3 4 5 6) 2)
 '(5 6)
 )

Reference

Lisp Data Structure

List

Specialized Lists

Vector

Sequence (List, Vector)

Hash Table