Skip to main content

make-list

make-list Function

Syntax:

make-list size &key initial-element → list

Arguments and Values:

size—a non-negative integer .

initial-element—an object. The default is nil.

list—a list.

Description:

Returns a list of length given by size, each of the elements of which is initial-element.

Examples:

(make-list 5)(NIL NIL NIL NIL NIL) 
(make-list 3 :initial-element ’rah)(RAH RAH RAH)
(make-list 2 :initial-element(1 2 3))((1 2 3) (1 2 3))
(make-list 0) → NIL ;*i.e.*, ()
(make-list 0 :initial-element ’new-element) → NIL

Exceptional Situations:

Should signal an error of type type-error if size is not a non-negative integer .

See Also:

cons, list

Expanded Reference: make-list

Basic usage

make-list creates a list of the given size. Each element defaults to NIL.

(make-list 5)
=> (NIL NIL NIL NIL NIL)

(make-list 0)
=> NIL

Specifying an initial element

The :initial-element keyword sets the value for every element of the new list.

(make-list 3 :initial-element 'x)
=> (X X X)

(make-list 4 :initial-element 0)
=> (0 0 0 0)

(make-list 2 :initial-element "hello")
=> (#1="hello" #1#)

Elements share the same object

All elements in the list are the same object (eq to each other). This matters for mutable initial elements.

(let ((lst (make-list 3 :initial-element (list 1 2))))
(eq (first lst) (second lst)))
=> T

Practical use: initializing a grid row

(make-list 8 :initial-element '-)
=> (- - - - - - - -)

Combining with mapcar for unique elements

If you need distinct mutable objects, use mapcar or loop instead.

(mapcar (lambda (x) (declare (ignore x)) (list 0))
(make-list 3))
=> ((0) (0) (0))