Emacs Lisp: List, Get Elements
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
- Cons Pair
- Quote and Dot Notation
- Proper List
- List
- Create List
- List, Get Elements
- Modify List
- Check Element Exist in List
- Remove Elements in List
- Backquote Reader Macro