Formal answer
In your expanded example you set the variable trees
to a new value in:
(setq trees '(pine birch))
That is not what happens in the original example. In the original example really the cdr of (nthcdr 2 trees)
is set.
If you want to assign the intermediate value to a variable for better understanding you should introduce a new one, e.g., trees-tail
would be an appropriate name:
(setq trees '(maple oak pine birch))
;; ⇒ (maple oak pine birch)
(setq trees-tail (nthcdr 2 trees))
;; ⇒ (pine birch)
(setcdr trees-tail nil)
;; trees-tail ⇒ (pine)
trees
;; ⇒ (maple oak pine)
Additional explanation
Note that lists are actually linked lists of conses. A cons is a construct of two cells, named car and cdr. The car is used for the value of the cons and the cdr is used to link to the next cons or it is set to nil to signal the end of the list.
After setting the value of trees
to the list (maple oak pine birch)
you have the following structure of linked conses:
The two-parted rectangles are the conses. The first part is the car the second is the cdr.
The value of trees
just refers to the first cons of the list.
After setting trees-tail
to the second cdr of the value of trees
it also points to the pine
-cons:
If we now set the cdr of trees-tail
to nil we break the link to the birch
-cons. That cons is no longer referred to by any variable or link and will be removed through the next garbage-collect
.
Additional Remarks
The car and the cdr of a cons are actually cells of the same structure. You can also set the car as link and get a tree structure instead of a list.
Example: (setq trees '(maple (birch) pine))
You can set the cdr of the last cons to a value instead of nil. Such a structure is called a dotted list.
Example: `(setq trees '(maple oak pine . birch))
In Common Lisp you shouldn't modify quoted lists (i.e., constant lists).
Instead of
(setq trees '(maple oak pine birch))
you would use
(setq trees (list 'maple 'oak 'pine 'pirch))
or
(setq trees (copy-list '(maple oak pine birch)))
The reason for that is the common subexpression optimization of lisp compilers.
The rules for Emacs lisp in that respect are not clearly stated in the Emacs lisp manual. There is already a discussion about that in another emacs.se question.
But since there are examples of structure modifications of quoted lists in the Elisp manual you are currently on the safe side.
Be aware that this might change in the future.