Node:length, Previous:Build a list, Up:cons

7.2.1 Find the Length of a List: length

You can find out how many elements there are in a list by using the Lisp function length, as in the following examples:

(length '(buttercup))
     => 1

(length '(daisy buttercup))
     => 2

(length (cons 'violet '(daisy buttercup)))
     => 3

In the third example, the cons function is used to construct a three element list which is then passed to the length function as its argument.

We can also use length to count the number of elements in an empty list:

(length ())
     => 0

As you would expect, the number of elements in an empty list is zero.

An interesting experiment is to find out what happens if you try to find the length of no list at all; that is, if you try to call length without giving it an argument, not even an empty list:

(length )

What you see, if you evaluate this, is the error message

Wrong number of arguments: #<subr length>, 0

This means that the function receives the wrong number of arguments, zero, when it expects some other number of arguments. In this case, one argument is expected, the argument being a list whose length the function is measuring. (Note that one list is one argument, even if the list has many elements inside it.)

The part of the error message that says #<subr length> is the name of the function. This is written with a special notation, #<subr, that indicates that the function length is one of the primitive functions written in C rather than in Emacs Lisp. (subr is an abbreviation for `subroutine'.) See What Is a Function, for more about subroutines.