length
length Function
Syntax:
length sequence → n
Arguments and Values:
sequence—a proper sequence.
n—a non-negative integer .
Description:
Returns the number of elements in sequence.
If sequence is a vector with a fill pointer , the active length as specified by the fill pointer is returned.
Examples:
(length "abc") → 3
(setq str (make-array ’(3) :element-type ’character
:initial-contents "abc"
:fill-pointer t)) → "abc"
(length str) → 3
(setf (fill-pointer str) 2) → 2
(length str) → 2
Exceptional Situations:
Should be prepared to signal an error of type type-error if sequence is not a proper sequence.
See Also:
list-length, sequence
reverse, nreverseExpanded Reference: length
Basic usage with lists and strings
length returns the number of elements in any proper sequence -- lists, vectors, and strings.
(length '(a b c d))
=> 4
(length "hello")
=> 5
(length #(1 2 3))
=> 3
(length nil)
=> 0
Empty sequences
An empty sequence always has length zero, regardless of type.
(length '())
=> 0
(length "")
=> 0
(length #())
=> 0
Length with a fill pointer
When a vector has a fill pointer, length returns the active length (the fill pointer value), not the total allocated size.
(let ((v (make-array 10 :fill-pointer 3)))
(length v))
=> 3
Strings are vectors of characters
Since strings are vectors, length works naturally on them. This includes strings with special characters.
(length "Common Lisp")
=> 11
(length (make-string 5 :initial-element #\x))
=> 5
Practical example: checking for empty sequences
length is commonly used to test whether a sequence has elements, though for lists null is more idiomatic.
(defun sequence-empty-p (seq)
(zerop (length seq)))
(sequence-empty-p '())
=> T
(sequence-empty-p "abc")
=> NIL
(sequence-empty-p #())
=> T