Skip to main content

copy-list

copy-list Function

Syntax:

copy-list list → copy

Arguments and Values:

list—a proper list or a dotted list.

copy—a list.

Description:

Returns a copy of list. If list is a dotted list, the resulting list will also be a dotted list.

Only the list structure of list is copied; the elements of the resulting list are the same as the corresponding elements of the given list.

Examples:

(setq lst (list 1 (list 2 3)))(1 (2 3)) 
(setq slst lst)(1 (2 3))
(setq clst (copy-list lst))(1 (2 3))
(eq slst lst) → true
(eq clst lst) → false
(equal clst lst) → true
(rplaca lst "one")("one" (2 3))
slst → ("one" (2 3))
clst → (1 (2 3))
(setf (caadr lst) "two")"two"
lst → ("one" ("two" 3))
slst → ("one" ("two" 3))
clst → (1 ("two" 3))

Exceptional Situations:

The consequences are undefined if list is a circular list.

See Also:

copy-alist, copy-seq, copy-tree

Notes:

The copy created is equal to list, but not eq.

list, list*∗*

Expanded Reference: copy-list

Creating a shallow copy of a list

copy-list creates a new list with the same elements but new cons cells at the top level. The elements themselves are not copied.

(let* ((original '(a b c))
(copy (copy-list original)))
(values copy
(equal original copy)
(eq original copy)))
=> (A B C)
=> T
=> NIL

Modifications to the copy do not affect the original

Since the top-level cons cells are new, structural changes to the copy leave the original unchanged.

(let* ((original (list 1 2 3))
(copy (copy-list original)))
(setf (car copy) 10)
(values original copy))
=> (1 2 3)
=> (10 2 3)

Shared substructure: nested lists are not copied

copy-list only copies the spine (top-level conses). Nested lists within the elements are shared between the original and the copy.

(let* ((original (list (list 1 2) (list 3 4)))
(copy (copy-list original)))
(setf (caar copy) 99)
(values original copy))
=> ((99 2) (3 4))
=> ((99 2) (3 4))

copy-list with dotted lists

copy-list preserves dotted list structure.

(copy-list '(a b . c))
=> (A B . C)

Practical use: safe destructive operations

Use copy-list to protect a list before performing destructive operations on it.

(let ((data '(3 1 4 1 5 9)))
(sort (copy-list data) #'<))
=> (1 1 3 4 5 9)

;; data is unchanged because we sorted a copy