push
push Macro
Syntax:
push item place → new-place-value
Arguments and Values:
item—an object.
place—a place, the value of which may be any object.
new-place-value—a list (the new value of place).
Description:
push prepends item to the list that is stored in place, stores the resulting list in place, and returns the list.
For information about the evaluation of subforms of place, see Section 5.1.1.1 (Evaluation of Subforms to Places).
Examples:
(setq llst ’(nil)) → (NIL)
(push 1 (car llst)) → (1)
llst → ((1))
(push 1 (car llst)) → (1 1)
llst → ((1 1))
(setq x ’(a (b c) d)) → (A (B C) D)
(push 5 (cadr x)) → (5 B C)
x → (A (5 B C) D)
Side Effects:
The contents of place are modified.
See Also:
pop, pushnew, Section 5.1 (Generalized Reference)
Notes:
The effect of (push item place) is equivalent to
(setf place (cons item place))
except that the subforms of place are evaluated only once, and item is evaluated before place.
Expanded Reference: push
Prepending an item to a list
push adds an item to the front of the list stored in a place, updates the place, and returns the new list.
(let ((lst '(b c d)))
(push 'a lst)
lst)
=> (A B C D)
Building a list with push
push is commonly used to build lists in reverse order.
(let ((result nil))
(push 3 result)
(push 2 result)
(push 1 result)
result)
=> (1 2 3)
push returns the new list
The return value of push is the new value of the place.
(let ((lst '(2 3)))
(push 1 lst))
=> (1 2 3)
push with generalized places
push works with any setf-able place, not just variables.
(let ((lst (list nil)))
(push 'a (car lst))
(push 'b (car lst))
lst)
=> ((B A))
Practical use: collecting results
push combined with nreverse is a common idiom for efficiently collecting results in order.
(let ((squares nil))
(dotimes (i 5)
(push (* (1+ i) (1+ i)) squares))
(nreverse squares))
=> (1 4 9 16 25)
push is equivalent to cons plus setf
(push item place) is equivalent to (setf place (cons item place)), except that the subforms of place are evaluated only once.
(let ((x '(2 3)))
(setf x (cons 1 x))
x)
=> (1 2 3)