Other Useful List Functions

Here are some more list-related Lisp functions that Emacs defines.

  • length returns 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
  • nthcdr calls cdr on a list n times.

    (nthcdr 2 '(a b c)) ⇒ (c)
  • nth returns the nth element of a list (where the first element is numbered zero). This is the same as the car of the nthcdr.

    (nth 2 '(a b c)) ⇒ c
    (nth 1 '((a b) (c d) (e f))) ⇒ (c d)
  • mapcar takes 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 of mapcar is 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")
  • equal tests whether its two arguments are equal. This is a different kind of equality test from eq, which we first encountered in the section called Saving and Restoring Point in Chapter 3. Whereas eq tests whether its arguments are the same object, equal tests 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))

    x and y are two different objects. That is, the first call to list creates a chain of three cons cells, and the second call to list creates a chain of three more ...

Get Writing GNU Emacs Extensions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.