Elisp: List, Get Elements
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 "a" "b" "c")) ;; "a"
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)
Drop Last N Items
butlast
-
(butlast list n)
drop the last n elements.
(butlast (list 0 1 2 3 4 5)) ;; (0 1 2 3 4) (butlast (list 0 1 2 3 4 5) 1) ;; (0 1 2 3 4) (butlast (list 0 1 2 3 4 5) 2) ;; (0 1 2 3)
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)
;; return a list with just the last item (last (list 3 4 5)) ;; (5) ;; get the actual last item (car (last (list 3 4 5))) ;; 5