Next: , Previous: , Up: car cdr & cons   [Contents][Index]


7.4 nth

The nthcdr function takes the CDR of a list repeatedly. The nth function takes the CAR of the result returned by nthcdr. It returns the Nth element of the list.

Thus, if it were not defined in C for speed, the definition of nth would be:

(defun nth (n list)
  "Returns the Nth element of LIST.
N counts from zero.  If LIST is not that long, nil is returned."
  (car (nthcdr n list)))

(Originally, nth was defined in Emacs Lisp in subr.el, but its definition was redone in C in the 1980s.)

The nth function returns a single element of a list. This can be very convenient.

Note that the elements are numbered from zero, not one. That is to say, the first element of a list, its CAR is the zeroth element. This zero-based counting often bothers people who are accustomed to the first element in a list being number one, which is one-based.

For example:

(nth 0 '("one" "two" "three"))
    ⇒ "one"

(nth 1 '("one" "two" "three"))
    ⇒ "two"

It is worth mentioning that nth, like nthcdr and cdr, does not change the original list—the function is non-destructive. This is in sharp contrast to the setcar and setcdr functions.

This page has generated for branch:work/add_lispintr, commit:65845cf60c073f2f3182d1d07483530e9bbe1d96 to check Japanese translation.