Other Useful List Functions
Here are some more list-related Lisp functions that Emacs defines.
lengthreturns the length of a list. It does not work on "improper" lists.(length nil) ⇒ 0 (length '(x y z)) ⇒ 3 (length '((x y z))) ⇒ 1 (length '(a b . c)) ⇒ error
nthcdrcallscdron a list n times.(nthcdr 2 '(a b c)) ⇒ (c)
nthreturns the nth element of a list (where the first element is numbered zero). This is the same as thecarof thenthcdr.(nth 2 '(a b c)) ⇒ c (nth 1 '((a b) (c d) (e f))) ⇒ (c d)
mapcartakes a function and a list as arguments. It calls the function once for each element of the list, passing that element as an argument to the function. The result ofmapcaris a list of the results of calling the function on each element. So if you have a list of strings and want to capitalize each one, you could write:(mapcar '(lambda (x) (capitalize x)) '("lisp" "is" "cool")) ⇒ ("Lisp" "Is" "Cool")equaltests whether its two arguments are equal. This is a different kind of equality test fromeq, which we first encountered in the section called Saving and Restoring Point in Chapter 3. Whereaseqtests whether its arguments are the same object,equaltests whether two objects have the same structure and contents.This distinction is important. In the following example:
(setq x (list 1 2 3)) (setq y (list 1 2 3))
xandyare two different objects. That is, the first call tolistcreates a chain of three cons cells, and the second call tolistcreates a chain of three more cons cells. So ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access