Next: , Previous: Setcar, Up: Modifying Lists

#### 5.6.2 Altering the CDR of a List

The lowest-level primitive for modifying a cdr is `setcdr`:

— Function: setcdr cons object

This function stores object as the new cdr of cons, replacing its previous cdr. In other words, it changes the cdr slot of cons to refer to object. It returns the value object.

Here is an example of replacing the cdr of a list with a different list. All but the first element of the list are removed in favor of a different sequence of elements. The first element is unchanged, because it resides in the car of the list, and is not reached via the cdr.

```     (setq x '(1 2 3))
⇒ (1 2 3)
(setcdr x '(4))
⇒ (4)
x
⇒ (1 4)
```

You can delete elements from the middle of a list by altering the cdrs of the cons cells in the list. For example, here we delete the second element, `b`, from the list `(a b c)`, by changing the cdr of the first cons cell:

```     (setq x1 '(a b c))
⇒ (a b c)
(setcdr x1 (cdr (cdr x1)))
⇒ (c)
x1
⇒ (a c)
```

Here is the result in box notation:

```                        --------------------
|                    |
--------------   |   --------------   |    --------------
| car   | cdr  |  |  | car   | cdr  |   -->| car   | cdr  |
|   a   |   o-----   |   b   |   o-------->|   c   |  nil |
|       |      |     |       |      |      |       |      |
--------------       --------------        --------------
```

The second cons cell, which previously held the element `b`, still exists and its car is still `b`, but it no longer forms part of this list.

It is equally easy to insert a new element by changing cdrs:

```     (setq x1 '(a b c))
⇒ (a b c)
(setcdr x1 (cons 'd (cdr x1)))
⇒ (d b c)
x1
⇒ (a d b c)
```

Here is this result in box notation:

```      --------------        -------------       -------------
| car  | cdr   |      | car  | cdr  |     | car  | cdr  |
|   a  |   o   |   -->|   b  |   o------->|   c  |  nil |
|      |   |   |  |   |      |      |     |      |      |
--------- | --   |    -------------       -------------
|      |
-----         --------
|                      |
|    ---------------   |
|   | car   | cdr   |  |
-->|   d   |   o------
|       |       |
---------------
```