ZetCode

Scheme pairs and lists

last modified November 24, 2026 Guile 3.0

The list is the central data structure of Scheme, and programs are written as lists too. A list is built from pairs, two-part cells created by cons. This article starts with pairs, shows how lists are made from them, and covers the standard procedures that access, join, reverse, and search lists. The data types article gave a first look at pairs and lists; here they are examined in depth. The examples run with GNU Guile 3.0.7.

Pairs

cons creates a pair from two values. car returns the first part and cdr the second. The names come from the machine instructions of the first Lisp implementation. A pair is printed in dotted notation, with the two parts separated by a dot.

pairs.scm
(define point (cons 3 4))

(write point)
(newline)
(write (car point))
(display " ")
(write (cdr point))
(newline)

(write (cons 1 (cons 2 3)))
(newline)
(write (cons 1 (cons 2 (cons 3 '()))))
(newline)
(write (cons (cons 1 2) (cons 3 4)))
(newline)
(write '(1 . (2 . (3 . ()))))
(newline)

A pair of 3 and 4 prints as (3 . 4). When the cdr of a pair is another pair, the printer leaves out the dot and the inner parentheses, so (cons 1 (cons 2 3)) prints as (1 2 . 3). When the chain ends with the empty list, no dot remains and the result is the list (1 2 3). A list is exactly that: a chain of pairs whose last cdr is '(). The last line writes the same list in full dotted notation, and the reader accepts it.

$ guile pairs.scm
(3 . 4)
3 4
(1 2 . 3)
(1 2 3)
((1 . 2) 3 . 4)
(1 2 3)

Building lists

Lists are created with a quoted literal, with list, which evaluates its arguments, or with make-list, which repeats a value. cons adds an element at the front of an existing list.

building.scm
(define colours '(red green blue))
(define sizes (list 'small 'medium (string-append "la" "rge")))
(define zeros (make-list 4 0))

(write colours)
(newline)
(write sizes)
(newline)
(write zeros)
(newline)
(write (cons 'black colours))
(newline)
(write colours)
(newline)
(write (list (+ 1 2) '(+ 1 2)))
(newline)
(write (list))
(newline)

sizes is built with list, so its last element is the result of string-append. cons returns a new list with black in front, and colours itself is unchanged. Inside a quoted list nothing is evaluated, which is why '(+ 1 2) stays a three-element list while (+ 1 2) becomes 3. (list) with no arguments returns the empty list.

$ guile building.scm
(red green blue)
(small medium "large")
(0 0 0 0)
(black red green blue)
(red green blue)
(3 (+ 1 2))
()

Accessing elements

length counts the elements, list-ref returns the element at an index from zero, and list-tail drops the first k elements. Combinations of car and cdr have short names: cadr means the car of the cdr, the second element.

access.scm
(define planets '(mercury venus earth mars jupiter saturn))

(write (length planets))
(newline)
(write (list-ref planets 0))
(display " ")
(write (list-ref planets 3))
(newline)
(write (list-tail planets 4))
(newline)
(write (car (cdr planets)))
(display " ")
(write (cadr planets))
(display " ")
(write (caddr planets))
(newline)
(write (cddr planets))
(newline)
(write (last-pair planets))
(newline)

list-ref must walk the list from the start, so reaching an element takes time proportional to its index; vectors are the structure for fast access by index. (car (cdr planets)) and (cadr planets) are the same, and caddr returns the third element. cddr drops two elements, and last-pair returns the last pair of the list, a list containing only the last element.

$ guile access.scm
6
mercury mars
(jupiter saturn)
venus venus earth
(earth mars jupiter saturn)
(saturn)

The cadr family

Scheme defines all combinations of up to four a and d letters between c and r. They are read from right to left: caddr takes the cdr twice and then the car. With nested lists they reach inner elements, and small accessor procedures give those positions names.

nested.scm
(define person '("Lucia" 34 ("Bratislava" "Slovakia")))

(define (person-name p) (car p))
(define (person-age p) (cadr p))
(define (person-city p) (car (caddr p)))
(define (person-country p) (cadr (caddr p)))

(display (person-name person))
(display ", ")
(display (person-age person))
(display ", ")
(display (person-city person))
(display ", ")
(display (person-country person))
(newline)

(define matrix '((1 2 3) (4 5 6)))

(write (caar matrix))
(display " ")
(write (cadar matrix))
(display " ")
(write (caadr matrix))
(newline)

A person is stored as a list of a name, an age, and a nested list with the city and the country. The accessors hide the positions, so the rest of the program does not need to know that the country is the cadr of the caddr. In the matrix, caar is the first element of the first row, cadar the second element of the first row, and caadr the first element of the second row. The records article shows a better way to store such data.

$ guile nested.scm
Lucia, 34, Bratislava, Slovakia
1 2 4

append and reverse

append joins any number of lists into one. reverse returns a list with the elements in the opposite order. Both return new lists and leave their arguments unchanged.

joining.scm
(define first-half '(1 2 3))
(define second-half '(4 5 6))

(write (append first-half second-half))
(newline)
(write (append '(a) '(b c) '() '(d e f)))
(newline)
(write (append first-half 7))
(newline)
(write (reverse second-half))
(newline)
(write (reverse '((1 2) (3 4))))
(newline)
(write first-half)
(newline)

(define (add-to-end lst item)
  (append lst (list item)))

(write (add-to-end '(x y) 'z))
(newline)

Empty lists contribute nothing to the result of append. Its last argument need not be a list: (append first-half 7) produces the improper list (1 2 3 . 7). reverse reverses only the top level, so the inner lists keep their order. add-to-end shows how to add an element at the end: wrap it in a list and append. This copies the whole list, so building a long list this way is slow; adding at the front and reversing once at the end is the usual alternative.

$ guile joining.scm
(1 2 3 4 5 6)
(a b c d e f)
(1 2 3 . 7)
(6 5 4)
((3 4) (1 2))
(1 2 3)
(x y z)

Searching with member

memq, memv, and member look for an element and return the rest of the list starting at the first match, or #f. They differ in the equality predicate they use: eq?, eqv?, and equal?, as described in the booleans and equality article.

searching.scm
(define fruits '(apple pear plum cherry))

(write (memq 'plum fruits))
(newline)
(write (memq 'kiwi fruits))
(newline)
(write (memv 3.0 '(1.0 2.0 3.0 4.0)))
(newline)
(write (memq "pear" '("apple" "pear")))
(newline)
(write (member "pear" '("apple" "pear" "plum")))
(newline)

(define (in-season? fruit)
  (if (memq fruit fruits) "in season" "not available"))

(display (list (in-season? 'pear) (in-season? 'mango)))
(newline)

memq finds the symbol plum and returns the list from there. memv is needed for inexact numbers. memq does not find the string "pear" in the second list, because the search key and the list element are separate string objects; member compares the contents and finds it. Since the result is either a list or #f, it can be used directly as a test, as in in-season?.

$ guile searching.scm
(plum cherry)
#f
(3.0 4.0)
#f
("pear" "plum")
(in season not available)

Looking up keys

A list of pairs is called an association list, or alist. The car of each pair is a key and the cdr its value. assq, assv, and assoc return the first pair whose key matches, or #f, again with eq?, eqv?, and equal?.

lookup.scm
(define capitals
  '((slovakia . "Bratislava")
    (hungary . "Budapest")
    (austria . "Vienna")))

(write (assq 'hungary capitals))
(newline)
(write (cdr (assq 'austria capitals)))
(newline)
(write (assq 'poland capitals))
(newline)

(define (capital-of country)
  (let ((entry (assq country capitals)))
    (if entry (cdr entry) "unknown")))

(display (list (capital-of 'slovakia) (capital-of 'poland)))
(newline)

(define codes '(("SK" . 421) ("HU" . 36) ("AT" . 43)))

(define code (string-append "H" "U"))

(write (assoc code codes))
(display " ")
(write (assq code codes))
(newline)

assq returns the whole pair, and cdr extracts the value. capital-of checks the result before taking its cdr, because (cdr #f) would be an error. The keys of codes are strings, and the key to look up is built at run time with string-append. assoc finds it by content, while assq compares identity and fails. The association lists article covers updating alists.

$ guile lookup.scm
(hungary . "Budapest")
"Vienna"
#f
(Bratislava unknown)
("HU" . 36) #f

Improper lists

A chain of pairs that does not end with the empty list is an improper list. It is a pair but not a list, and procedures that expect a list reject it.

improper.scm
(define proper '(1 2 3))
(define dotted '(1 2 . 3))

(write (list (pair? proper) (list? proper)))
(newline)
(write (list (pair? dotted) (list? dotted)))
(newline)
(write (cdr (cdr dotted)))
(newline)
(write (list (list? '()) (pair? '())))
(newline)
(write (length proper))
(newline)
(write (length dotted))
(newline)

Both values are pairs, but only proper satisfies list?. Taking the cdr twice from dotted reaches the number 3 instead of the empty list. The empty list, on the other hand, is a list but not a pair. length works on the proper list and fails on the improper one with a wrong type error. The backtrace is left out.

$ guile improper.scm
(#t #t)
(#t #f)
3
(#t #f)
3
ERROR: In procedure length:
In procedure length: Wrong type argument in position 1: (1 2 . 3)

Shared structure

cons does not copy the list it extends: the new pair points to the existing one. append copies all its arguments except the last, which it shares. The sharing is invisible until a list is modified with set-car! or set-cdr!, which replace the parts of a pair.

sharing.scm
(define tail (list 2 3))
(define numbers (cons 1 tail))
(define joined (append (list 0) numbers))

(write (eq? (cdr numbers) tail))
(newline)
(write (eq? (cdr joined) numbers))
(newline)

(set-car! tail 20)
(write numbers)
(display " ")
(write joined)
(newline)

(define copy (list-copy numbers))
(set-cdr! numbers '())
(write numbers)
(display " ")
(write copy)
(newline)

eq? confirms that the cdr of numbers is the very list tail, and that joined shares numbers. Changing the first element of tail to 20 therefore changes all three lists. list-copy creates new pairs, so cutting numbers short with set-cdr! does not affect the copy. The lists are built with list because literal constants must not be modified.

$ guile sharing.scm
#t
#t
(1 20 3) (0 1 20 3)
(1) (1 20 3)

Writing list procedures

The procedures of this article, together with recursion and named let, are enough to write new list operations. The next program defines three of them; their names do not collide with built-in procedures.

procs.scm
(define (position-of item lst)
  (let loop ((rest lst) (index 0))
    (cond ((null? rest) #f)
          ((equal? (car rest) item) index)
          (else (loop (cdr rest) (+ index 1))))))

(define (remove-item item lst)
  (cond ((null? lst) '())
        ((equal? (car lst) item) (remove-item item (cdr lst)))
        (else (cons (car lst) (remove-item item (cdr lst))))))

(define (first-n lst n)
  (if (or (= n 0) (null? lst))
      '()
      (cons (car lst) (first-n (cdr lst) (- n 1)))))

(define data '(3 1 4 1 5 9 2 6 5 3 5))

(write (list (position-of 9 data) (position-of 7 data)))
(newline)
(write (remove-item 5 data))
(newline)
(write (first-n data 4))
(newline)

position-of is a loop that counts the index and returns #f when the item is missing. remove-item builds a new list without the given item and skips every occurrence of it. first-n takes the first n elements and stops early if the list is shorter. The procedures compare elements with equal?, so they work for numbers, strings, and lists alike.

$ guile procs.scm
(5 #f)
(3 1 4 1 9 2 6 3)
(3 1 4 1)

Source

Lists — GNU Guile Reference Manual

R7RS: the Revised7 Report on Scheme

In this article we have built pairs and lists with cons, list, and make-list, accessed elements with list-ref and the cadr family, joined and reversed lists, searched them with member and assoc, met improper lists and shared structure, and written new list procedures. The recursion and tail calls and iteration articles explain the techniques used to process lists, and the SRFI 1 list library article covers the extended list procedures.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.