# How does a list end in nil?

I believe Emacs lists have `nil` at their end. That said, I was trying to test examples.
Can anyone tell the difference between `a` and `b`?

``````(setq a '(foo))
(setq b '(foo nil))

;; Returns nil and (nil), respectively.
(cdr a)
(cdr b)
``````
• a is `(foo . nil)`. b is `(foo . (nil . nil))`. Apr 15, 2020 at 18:39
• And `(cdr nil)` and `(car nil)` return `nil` (by convention, for convenience).
– Drew
Apr 15, 2020 at 20:02
– Drew
Apr 15, 2020 at 20:03
• `a` is a list with one element: `foo`. `b` is a list with two elements: `foo` and `nil`.
– Drew
Apr 15, 2020 at 20:04

It is in a sense true that a proper list ends in `nil`, but not in the sense that the last element of every proper list is `nil`. It is the cdr of the innermost cons of the proper list that is `nil`. A cons is a car-cdr pair. A proper list is a nest of conses, or rather, a proper list is either nil or a cons whose cdr is a proper list. So a finite proper list is a nest of conses whose innermost cons's cdr is nil. Its elements are its cars. The proper list `(a b c)` is a cons whose car is `a` and whose cdr is `(b c)`, whose cdr is `(c)`, whose cdr is `nil`. The last element is `c`, not `nil`; but the last (or innermost) cdr is indeed `nil`; this is what ends a proper list.

In dotted-pair notation, which shows the cons structure of a list, `(a b c)` is `(a . (b . (c . nil)))`.

A list simpliciter is either `nil` or a cons whose cdr is not necessarily a list.

Your `a` is `(foo . nil)` and your `b` is `(foo . (nil . nil))`.

And `(cdr b)` is `(nil)` because `(nil . nil)` is `(nil)`, the list whose only element is `nil`.

For more on conses, evaluate `(info "(elisp) Cons Cell Type")`.

• I think it would be useful to link to `(info "(elisp) Cons Cell Type")` and subnodes. Apr 15, 2020 at 22:34
• @phils, Graham calls it dot notation. Apr 16, 2020 at 0:03
• @Toothrot Fair enough -- please change it back if you prefer. It's always "dotted pair notation" in the elisp manual, which is why I edited that, but I think it's good either way. Apr 16, 2020 at 0:22