2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @setfilename ../info/lists
6 @node Lists, Sequences Arrays Vectors, Strings and Characters, Top
9 @cindex element (of list)
11 A @dfn{list} represents a sequence of zero or more elements (which may
12 be any Lisp objects). The important difference between lists and
13 vectors is that two or more lists can share part of their structure; in
14 addition, you can insert or delete elements in a list without copying
18 * Cons Cells:: How lists are made out of cons cells.
19 * Lists as Boxes:: Graphical notation to explain lists.
20 * List-related Predicates:: Is this object a list? Comparing two lists.
21 * List Elements:: Extracting the pieces of a list.
22 * Building Lists:: Creating list structure.
23 * Modifying Lists:: Storing new pieces into an existing list.
24 * Sets And Lists:: A list can represent a finite mathematical set.
25 * Association Lists:: A list can represent a finite relation or mapping.
29 @section Lists and Cons Cells
30 @cindex lists and cons cells
31 @cindex @code{nil} and lists
33 Lists in Lisp are not a primitive data type; they are built up from
34 @dfn{cons cells}. A cons cell is a data object which represents an ordered
35 pair. It records two Lisp objects, one labeled as the @sc{car}, and the
36 other labeled as the @sc{cdr}. These names are traditional; @sc{cdr} is
37 pronounced ``could-er.''
39 A list is a series of cons cells chained together, one cons cell per
40 element of the list. By convention, the @sc{car}s of the cons cells are
41 the elements of the list, and the @sc{cdr}s are used to chain the list:
42 the @sc{cdr} of each cons cell is the following cons cell. The @sc{cdr}
43 of the last cons cell is @code{nil}. This asymmetry between the
44 @sc{car} and the @sc{cdr} is entirely a matter of convention; at the
45 level of cons cells, the @sc{car} and @sc{cdr} slots have the same
48 The symbol @code{nil} is considered a list as well as a symbol; it is
49 the list with no elements. For convenience, the symbol @code{nil} is
50 considered to have @code{nil} as its @sc{cdr} (and also as its
53 The @sc{cdr} of any nonempty list @var{l} is a list containing all the
54 elements of @var{l} except the first.
57 @comment node-name, next, previous, up
58 @section Lists as Linked Pairs of Boxes
59 @cindex box representation for lists
60 @cindex lists represented as boxes
61 @cindex cons cell as box
63 A cons cell can be illustrated as a pair of boxes. The first box
64 represents the @sc{car} and the second box represents the @sc{cdr}.
65 Here is an illustration of the two-element list, @code{(tulip lily)},
66 made from two cons cells:
70 --------------- ---------------
71 | car | cdr | | car | cdr |
72 | tulip | o---------->| lily | nil |
74 --------------- ---------------
78 Each pair of boxes represents a cons cell. Each box ``refers to'',
79 ``points to'' or ``contains'' a Lisp object. (These terms are
80 synonymous.) The first box, which is the @sc{car} of the first cons
81 cell, contains the symbol @code{tulip}. The arrow from the @sc{cdr} of
82 the first cons cell to the second cons cell indicates that the @sc{cdr}
83 of the first cons cell points to the second cons cell.
85 The same list can be illustrated in a different sort of box notation
91 |___|___|--> |___|___|--> nil
98 Here is a more complex illustration, showing the three-element list,
99 @code{((pine needles) oak maple)}, the first element of which is a
104 ___ ___ ___ ___ ___ ___
105 |___|___|--> |___|___|--> |___|___|--> nil
111 --> |___|___|--> |___|___|--> nil
118 The same list represented in the first box notation looks like this:
122 -------------- -------------- --------------
123 | car | cdr | | car | cdr | | car | cdr |
124 | o | o------->| oak | o------->| maple | nil |
126 -- | --------- -------------- --------------
129 | -------------- ----------------
130 | | car | cdr | | car | cdr |
131 ------>| pine | o------->| needles | nil |
133 -------------- ----------------
137 @xref{List Type}, for the read and print syntax of lists, and for more
138 ``box and arrow'' illustrations of lists.
140 @node List-related Predicates
141 @section Predicates on Lists
143 The following predicates test whether a Lisp object is an atom, is a
144 cons cell or is a list, or whether it is the distinguished object
145 @code{nil}. (Many of these predicates can be defined in terms of the
146 others, but they are used so often that it is worth having all of them.)
149 This function returns @code{t} if @var{object} is a cons cell, @code{nil}
150 otherwise. @code{nil} is not a cons cell, although it @emph{is} a list.
155 This function returns @code{t} if @var{object} is an atom, @code{nil}
156 otherwise. All objects except cons cells are atoms. The symbol
157 @code{nil} is an atom and is also a list; it is the only Lisp object
161 (atom @var{object}) @equiv{} (not (consp @var{object}))
166 This function returns @code{t} if @var{object} is a cons cell or
167 @code{nil}. Otherwise, it returns @code{nil}.
182 This function is the opposite of @code{listp}: it returns @code{t} if
183 @var{object} is not a list. Otherwise, it returns @code{nil}.
186 (listp @var{object}) @equiv{} (not (nlistp @var{object}))
191 This function returns @code{t} if @var{object} is @code{nil}, and
192 returns @code{nil} otherwise. This function is identical to @code{not},
193 but as a matter of clarity we use @code{null} when @var{object} is
194 considered a list and @code{not} when it is considered a truth value
195 (see @code{not} in @ref{Combining Conditions}).
212 @section Accessing Elements of Lists
213 @cindex list elements
216 This function returns the value pointed to by the first pointer of the
217 cons cell @var{cons-cell}. Expressed another way, this function
218 returns the @sc{car} of @var{cons-cell}.
220 As a special case, if @var{cons-cell} is @code{nil}, then @code{car}
221 is defined to return @code{nil}; therefore, any list is a valid argument
222 for @code{car}. An error is signaled if the argument is not a cons cell
238 This function returns the value pointed to by the second pointer of
239 the cons cell @var{cons-cell}. Expressed another way, this function
240 returns the @sc{cdr} of @var{cons-cell}.
242 As a special case, if @var{cons-cell} is @code{nil}, then @code{cdr}
243 is defined to return @code{nil}; therefore, any list is a valid argument
244 for @code{cdr}. An error is signaled if the argument is not a cons cell
259 @defun car-safe object
260 This function lets you take the @sc{car} of a cons cell while avoiding
261 errors for other data types. It returns the @sc{car} of @var{object} if
262 @var{object} is a cons cell, @code{nil} otherwise. This is in contrast
263 to @code{car}, which signals an error if @var{object} is not a list.
267 (car-safe @var{object})
269 (let ((x @var{object}))
277 @defun cdr-safe object
278 This function lets you take the @sc{cdr} of a cons cell while
279 avoiding errors for other data types. It returns the @sc{cdr} of
280 @var{object} if @var{object} is a cons cell, @code{nil} otherwise.
281 This is in contrast to @code{cdr}, which signals an error if
282 @var{object} is not a list.
286 (cdr-safe @var{object})
288 (let ((x @var{object}))
297 This function returns the @var{n}th element of @var{list}. Elements
298 are numbered starting with zero, so the @sc{car} of @var{list} is
299 element number zero. If the length of @var{list} is @var{n} or less,
300 the value is @code{nil}.
302 If @var{n} is negative, @code{nth} returns the first element of
318 (nth n x) @equiv{} (car (nthcdr n x))
324 This function returns the @var{n}th @sc{cdr} of @var{list}. In other
325 words, it removes the first @var{n} links of @var{list} and returns
328 If @var{n} is zero or negative, @code{nthcdr} returns all of
329 @var{list}. If the length of @var{list} is @var{n} or less,
330 @code{nthcdr} returns @code{nil}.
334 (nthcdr 1 '(1 2 3 4))
338 (nthcdr 10 '(1 2 3 4))
342 (nthcdr -3 '(1 2 3 4))
349 @comment node-name, next, previous, up
350 @section Building Cons Cells and Lists
352 @cindex building lists
354 Many functions build lists, as lists reside at the very heart of Lisp.
355 @code{cons} is the fundamental list-building function; however, it is
356 interesting to note that @code{list} is used more times in the source
357 code for Emacs than @code{cons}.
359 @defun cons object1 object2
360 This function is the fundamental function used to build new list
361 structure. It creates a new cons cell, making @var{object1} the
362 @sc{car}, and @var{object2} the @sc{cdr}. It then returns the new cons
363 cell. The arguments @var{object1} and @var{object2} may be any Lisp
364 objects, but most often @var{object2} is a list.
382 @code{cons} is often used to add a single element to the front of a
383 list. This is called @dfn{consing the element onto the list}. For
387 (setq list (cons newelt list))
390 Note that there is no conflict between the variable named @code{list}
391 used in this example and the function named @code{list} described below;
392 any symbol can serve both purposes.
395 @defun list &rest objects
396 This function creates a list with @var{objects} as its elements. The
397 resulting list is always @code{nil}-terminated. If no @var{objects}
398 are given, the empty list is returned.
403 @result{} (1 2 3 4 5)
406 (list 1 2 '(3 4 5) 'foo)
407 @result{} (1 2 (3 4 5) foo)
416 @defun make-list length object
417 This function creates a list of length @var{length}, in which all the
418 elements have the identical value @var{object}. Compare
419 @code{make-list} with @code{make-string} (@pxref{Creating Strings}).
424 @result{} (pigs pigs pigs)
433 @defun append &rest sequences
434 @cindex copying lists
435 This function returns a list containing all the elements of
436 @var{sequences}. The @var{sequences} may be lists, vectors, or strings.
437 All arguments except the last one are copied, so none of them are
440 The final argument to @code{append} may be any object but it is
441 typically a list. The final argument is not copied or converted; it
442 becomes part of the structure of the new list.
448 (setq trees '(pine oak))
450 (setq more-trees (append '(maple birch) trees))
451 @result{} (maple birch pine oak)
458 @result{} (maple birch pine oak)
461 (eq trees (cdr (cdr more-trees)))
466 You can see what happens by looking at a box diagram. The variable
467 @code{trees} is set to the list @code{(pine oak)} and then the variable
468 @code{more-trees} is set to the list @code{(maple birch pine oak)}.
469 However, the variable @code{trees} continues to refer to the original
476 | ___ ___ ___ ___ -> ___ ___ ___ ___
477 --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil
480 --> maple -->birch --> pine --> oak
484 An empty sequence contributes nothing to the value returned by
485 @code{append}. As a consequence of this, a final @code{nil} argument
486 forces a copy of the previous argument.
494 (setq wood (append trees ()))
508 This once was the usual way to copy a list, before the function
509 @code{copy-sequence} was invented. @xref{Sequences Arrays Vectors}.
511 With the help of @code{apply}, we can append all the lists in a list of
516 (apply 'append '((a b c) nil (x y z) nil))
517 @result{} (a b c x y z)
521 If no @var{sequences} are given, @code{nil} is returned:
530 See @code{nconc} in @ref{Rearrangement}, for a way to join lists with no
533 Integers are also allowed as arguments to @code{append}. They are
534 converted to strings of digits making up the decimal print
535 representation of the integer, and these strings are then appended.
540 (setq trees '(pine oak))
548 (setq longer-list (append trees 6 '(spruce)))
549 @result{} (pine oak 54 spruce)
552 (setq x-list (append trees 6 6))
553 @result{} (pine oak 54 . 6)
557 This special case exists for compatibility with Mocklisp, and we don't
558 recommend you take advantage of it. If you want to convert an integer
559 in this way, use @code{format} (@pxref{Formatting Strings}) or
560 @code{number-to-string} (@pxref{String Conversion}).
564 This function creates a new list whose elements are the elements of
565 @var{list}, but in reverse order. The original argument @var{list} is
582 @node Modifying Lists
583 @section Modifying Existing List Structure
585 You can modify the @sc{car} and @sc{cdr} contents of a cons cell with the
586 primitives @code{setcar} and @code{setcdr}.
588 @cindex CL note---@code{rplaca} vrs @code{setcar}
592 @b{Common Lisp note:} Common Lisp uses functions @code{rplaca} and
593 @code{rplacd} to alter list structure; they change structure the same
594 way as @code{setcar} and @code{setcdr}, but the Common Lisp functions
595 return the cons cell while @code{setcar} and @code{setcdr} return the
596 new @sc{car} or @sc{cdr}.
600 * Setcar:: Replacing an element in a list.
601 * Setcdr:: Replacing part of the list backbone.
602 This can be used to remove or add elements.
603 * Rearrangement:: Reordering the elements in a list; combining lists.
607 @subsection Altering List Elements with @code{setcar}
609 Changing the @sc{car} of a cons cell is done with @code{setcar}, which
610 replaces one element of a list with a different element.
612 @defun setcar cons object
613 This function stores @var{object} as the new @sc{car} of @var{cons},
614 replacing its previous @sc{car}. It returns the value @var{object}.
633 When a cons cell is part of the shared structure of several lists,
634 storing a new @sc{car} into the cons changes one element of each of
635 these lists. Here is an example:
639 ;; @r{Create two lists that are partly shared.}
642 (setq x2 (cons 'z (cdr x1)))
647 ;; @r{Replace the @sc{car} of a shared link.}
648 (setcar (cdr x1) 'foo)
650 x1 ; @r{Both lists are changed.}
657 ;; @r{Replace the @sc{car} of a link that is not shared.}
660 x1 ; @r{Only one list is changed.}
661 @result{} (baz foo c)
667 Here is a graphical depiction of the shared structure of the two lists
668 in the variables @code{x1} and @code{x2}, showing why replacing @code{b}
673 ___ ___ ___ ___ ___ ___
674 x1---> |___|___|----> |___|___|--> |___|___|--> nil
687 Here is an alternative form of box diagram, showing the same relationship:
692 -------------- -------------- --------------
693 | car | cdr | | car | cdr | | car | cdr |
694 | a | o------->| b | o------->| c | nil |
696 -------------- | -------------- --------------
708 @subsection Altering the CDR of a List
710 The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}:
712 @defun setcdr cons object
713 This function stores @var{object} into the @sc{cdr} of @var{cons}. The
714 value returned is @var{object}, not @var{cons}.
717 Here is an example of replacing the @sc{cdr} of a list with a
718 different list. All but the first element of the list are removed in
719 favor of a different sequence of elements. The first element is
720 unchanged, because it resides in the @sc{car} of the list, and is not
721 reached via the @sc{cdr}.
738 You can delete elements from the middle of a list by altering the
739 @sc{cdr}s of the cons cells in the list. For example, here we delete
740 the second element, @code{b}, from the list @code{(a b c)}, by changing
741 the @sc{cdr} of the first cell:
747 (setcdr x1 (cdr (cdr x1)))
754 Here is the result in box notation:
760 -------------- | -------------- | --------------
761 | car | cdr | | | car | cdr | -->| car | cdr |
762 | a | o----- | b | o-------->| c | nil |
764 -------------- -------------- --------------
769 The second cons cell, which previously held the element @code{b}, still
770 exists and its @sc{car} is still @code{b}, but it no longer forms part
773 It is equally easy to insert a new element by changing @sc{cdr}s:
779 (setcdr x1 (cons 'd (cdr x1)))
786 Here is this result in box notation:
790 -------------- ------------- -------------
791 | car | cdr | | car | cdr | | car | cdr |
792 | a | o | -->| b | o------->| c | nil |
793 | | | | | | | | | | |
794 --------- | -- | ------------- -------------
807 @subsection Functions that Rearrange Lists
808 @cindex rearrangement of lists
809 @cindex modification of lists
811 Here are some functions that rearrange lists ``destructively'' by
812 modifying the @sc{cdr}s of their component cons cells. We call these
813 functions ``destructive'' because they chew up the original lists passed
814 to them as arguments, to produce a new list that is the returned value.
816 @defun nconc &rest lists
817 @cindex concatenating lists
818 @cindex joining lists
819 This function returns a list containing all the elements of @var{lists}.
820 Unlike @code{append} (@pxref{Building Lists}), the @var{lists} are
821 @emph{not} copied. Instead, the last @sc{cdr} of each of the
822 @var{lists} is changed to refer to the following list. The last of the
823 @var{lists} is not altered. For example:
832 @result{} (1 2 3 4 5)
836 @result{} (1 2 3 4 5)
840 Since the last argument of @code{nconc} is not itself modified, it is
841 reasonable to use a constant list, such as @code{'(4 5)}, as in the
842 above example. For the same reason, the last argument need not be a
852 @result{} (1 2 3 . z)
856 @result{} (1 2 3 . z)
860 A common pitfall is to use a quoted constant list as a non-last
861 argument to @code{nconc}. If you do this, your program will change
862 each time you run it! Here is what happens:
866 (defun add-foo (x) ; @r{We want this function to add}
867 (nconc '(foo) x)) ; @r{@code{foo} to the front of its arg.}
871 (symbol-function 'add-foo)
872 @result{} (lambda (x) (nconc (quote (foo)) x))
876 (setq xx (add-foo '(1 2))) ; @r{It seems to work.}
880 (setq xy (add-foo '(3 4))) ; @r{What happened?}
881 @result{} (foo 1 2 3 4)
889 (symbol-function 'add-foo)
890 @result{} (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
896 @cindex reversing a list
897 This function reverses the order of the elements of @var{list}.
898 Unlike @code{reverse}, @code{nreverse} alters its argument destructively
899 by reversing the @sc{cdr}s in the cons cells forming the list. The cons
900 cell which used to be the last one in @var{list} becomes the first cell
917 ;; @r{The cell that was first is now last.}
923 To avoid confusion, we usually store the result of @code{nreverse}
924 back in the same variable which held the original list:
927 (setq x (nreverse x))
930 Here is the @code{nreverse} of our favorite example, @code{(a b c)},
931 presented graphically:
935 @r{Original list head:} @r{Reversed list:}
936 ------------- ------------- ------------
937 | car | cdr | | car | cdr | | car | cdr |
938 | a | nil |<-- | b | o |<-- | c | o |
939 | | | | | | | | | | | | |
940 ------------- | --------- | - | -------- | -
942 ------------- ------------
947 @defun sort list predicate
949 @cindex sorting lists
950 This function sorts @var{list} stably, though destructively, and
951 returns the sorted list. It compares elements using @var{predicate}. A
952 stable sort is one in which elements with equal sort keys maintain their
953 relative order before and after the sort. Stability is important when
954 successive sorts are used to order elements according to different
957 The argument @var{predicate} must be a function that accepts two
958 arguments. It is called with two elements of @var{list}. To get an
959 increasing order sort, the @var{predicate} should return @code{t} if the
960 first element is ``less than'' the second, or @code{nil} if not.
962 The destructive aspect of @code{sort} is that it rearranges the cons
963 cells forming @var{list} by changing @sc{cdr}s. A nondestructive sort
964 function would create new cons cells to store the elements in their
965 sorted order. If you wish to make a sorted copy without destroying the
966 original, copy it first with @code{copy-sequence} and then sort.
968 Sorting does not change the @sc{car}s of the cons cells in @var{list};
969 the cons cell that originally contained the element @code{a} in
970 @var{list} still has @code{a} in its @sc{car} after sorting, but it now
971 appears in a different position in the list due to the change of
972 @sc{cdr}s. For example:
976 (setq nums '(1 3 2 6 5 4 0))
977 @result{} (1 3 2 6 5 4 0)
981 @result{} (0 1 2 3 4 5 6)
985 @result{} (1 2 3 4 5 6)
990 Note that the list in @code{nums} no longer contains 0; this is the same
991 cons cell that it was before, but it is no longer the first one in the
992 list. Don't assume a variable that formerly held the argument now holds
993 the entire sorted list! Instead, save the result of @code{sort} and use
994 that. Most often we store the result back into the variable that held
998 (setq nums (sort nums '<))
1001 @xref{Sorting}, for more functions that perform sorting.
1002 See @code{documentation} in @ref{Accessing Documentation}, for a
1003 useful example of @code{sort}.
1007 See @code{delq}, in @ref{Sets And Lists}, for another function
1008 that modifies cons cells.
1011 The function @code{delq} in the following section is another example
1012 of destructive list manipulation.
1015 @node Sets And Lists
1016 @section Using Lists as Sets
1017 @cindex lists as sets
1020 A list can represent an unordered mathematical set---simply consider a
1021 value an element of a set if it appears in the list, and ignore the
1022 order of the list. To form the union of two sets, use @code{append} (as
1023 long as you don't mind having duplicate elements). Other useful
1024 functions for sets include @code{memq} and @code{delq}, and their
1025 @code{equal} versions, @code{member} and @code{delete}.
1027 @cindex CL note---lack @code{union}, @code{set}
1029 @b{Common Lisp note:} Common Lisp has functions @code{union} (which
1030 avoids duplicate elements) and @code{intersection} for set operations,
1031 but GNU Emacs Lisp does not have them. You can write them in Lisp if
1035 @defun memq object list
1036 @cindex membership in a list
1037 This function tests to see whether @var{object} is a member of
1038 @var{list}. If it is, @code{memq} returns a list starting with the
1039 first occurrence of @var{object}. Otherwise, it returns @code{nil}.
1040 The letter @samp{q} in @code{memq} says that it uses @code{eq} to
1041 compare @var{object} against the elements of the list. For example:
1045 (memq 2 '(1 2 3 2 1))
1049 (memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1055 @defun delq object list
1056 @cindex deletion of elements
1057 This function destructively removes all elements @code{eq} to
1058 @var{object} from @var{list}. The letter @samp{q} in @code{delq} says
1059 that it uses @code{eq} to compare @var{object} against the elements of
1060 the list, like @code{memq}.
1063 When @code{delq} deletes elements from the front of the list, it does so
1064 simply by advancing down the list and returning a sublist that starts
1065 after those elements:
1069 (delq 'a '(a b c)) @equiv{} (cdr '(a b c))
1073 When an element to be deleted appears in the middle of the list,
1074 removing it involves changing the @sc{cdr}s (@pxref{Setcdr}).
1078 (setq sample-list '(1 2 3 (4)))
1079 @result{} (1 2 3 (4))
1082 (delq 1 sample-list)
1087 @result{} (1 2 3 (4))
1090 (delq 2 sample-list)
1099 Note that @code{(delq 2 sample-list)} modifies @code{sample-list} to
1100 splice out the second element, but @code{(delq 1 sample-list)} does not
1101 splice anything---it just returns a shorter list. Don't assume that a
1102 variable which formerly held the argument @var{list} now has fewer
1103 elements, or that it still holds the original list! Instead, save the
1104 result of @code{delq} and use that. Most often we store the result back
1105 into the variable that held the original list:
1108 (setq flowers (delq 'rose flowers))
1111 In the following example, the @code{(4)} that @code{delq} attempts to match
1112 and the @code{(4)} in the @code{sample-list} are not @code{eq}:
1116 (delq '(4) sample-list)
1121 The following two functions are like @code{memq} and @code{delq} but use
1122 @code{equal} rather than @code{eq} to compare elements. They are new in
1125 @defun member object list
1126 The function @code{member} tests to see whether @var{object} is a member
1127 of @var{list}, comparing members with @var{object} using @code{equal}.
1128 If @var{object} is a member, @code{member} returns a list starting with
1129 its first occurrence in @var{list}. Otherwise, it returns @code{nil}.
1131 Compare this with @code{memq}:
1135 (member '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are @code{equal}.}
1139 (memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1143 ;; @r{Two strings with the same contents are @code{equal}.}
1144 (member "foo" '("foo" "bar"))
1145 @result{} ("foo" "bar")
1150 @defun delete object list
1151 This function destructively removes all elements @code{equal} to
1152 @var{object} from @var{list}. It is to @code{delq} as @code{member} is
1153 to @code{memq}: it uses @code{equal} to compare elements with
1154 @var{object}, like @code{member}; when it finds an element that matches,
1155 it removes the element just as @code{delq} would. For example:
1159 (delete '(2) '((2) (1) (2)))
1166 @b{Common Lisp note:} The functions @code{member} and @code{delete} in
1167 GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common
1168 Lisp versions do not use @code{equal} to compare elements.
1171 @node Association Lists
1172 @section Association Lists
1173 @cindex association list
1176 An @dfn{association list}, or @dfn{alist} for short, records a mapping
1177 from keys to values. It is a list of cons cells called
1178 @dfn{associations}: the @sc{car} of each cell is the @dfn{key}, and the
1179 @sc{cdr} is the @dfn{associated value}.@footnote{This usage of ``key''
1180 is not related to the term ``key sequence''; it means a value used to
1181 look up an item in a table. In this case, the table is the alist, and
1182 the alist associations are the items.}
1184 Here is an example of an alist. The key @code{pine} is associated with
1185 the value @code{cones}; the key @code{oak} is associated with
1186 @code{acorns}; and the key @code{maple} is associated with @code{seeds}.
1196 The associated values in an alist may be any Lisp objects; so may the
1197 keys. For example, in the following alist, the symbol @code{a} is
1198 associated with the number @code{1}, and the string @code{"b"} is
1199 associated with the @emph{list} @code{(2 3)}, which is the @sc{cdr} of
1206 Sometimes it is better to design an alist to store the associated
1207 value in the @sc{car} of the @sc{cdr} of the element. Here is an
1211 '((rose red) (lily white) (buttercup yellow))
1215 Here we regard @code{red} as the value associated with @code{rose}. One
1216 advantage of this method is that you can store other related
1217 information---even a list of other items---in the @sc{cdr} of the
1218 @sc{cdr}. One disadvantage is that you cannot use @code{rassq} (see
1219 below) to find the element containing a given value. When neither of
1220 these considerations is important, the choice is a matter of taste, as
1221 long as you are consistent about it for any given alist.
1223 Note that the same alist shown above could be regarded as having the
1224 associated value in the @sc{cdr} of the element; the value associated
1225 with @code{rose} would be the list @code{(red)}.
1227 Association lists are often used to record information that you might
1228 otherwise keep on a stack, since new associations may be added easily to
1229 the front of the list. When searching an association list for an
1230 association with a given key, the first one found is returned, if there
1233 In Emacs Lisp, it is @emph{not} an error if an element of an
1234 association list is not a cons cell. The alist search functions simply
1235 ignore such elements. Many other versions of Lisp signal errors in such
1238 Note that property lists are similar to association lists in several
1239 respects. A property list behaves like an association list in which
1240 each key can occur only once. @xref{Property Lists}, for a comparison
1241 of property lists and association lists.
1243 @defun assoc key alist
1244 This function returns the first association for @var{key} in
1245 @var{alist}. It compares @var{key} against the alist elements using
1246 @code{equal} (@pxref{Equality Predicates}). It returns @code{nil} if no
1247 association in @var{alist} has a @sc{car} @code{equal} to @var{key}.
1251 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1252 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1254 @result{} (oak . acorns)
1255 (cdr (assoc 'oak trees))
1257 (assoc 'birch trees)
1261 Here is another example in which the keys and values are not symbols:
1264 (setq needles-per-cluster
1265 '((2 "Austrian Pine" "Red Pine")
1269 (cdr (assoc 3 needles-per-cluster))
1270 @result{} ("Pitch Pine")
1271 (cdr (assoc 2 needles-per-cluster))
1272 @result{} ("Austrian Pine" "Red Pine")
1276 @defun assq key alist
1277 This function is like @code{assoc} in that it returns the first
1278 association for @var{key} in @var{alist}, but it makes the comparison
1279 using @code{eq} instead of @code{equal}. @code{assq} returns @code{nil}
1280 if no association in @var{alist} has a @sc{car} @code{eq} to @var{key}.
1281 This function is used more often than @code{assoc}, since @code{eq} is
1282 faster than @code{equal} and most alists use symbols as keys.
1283 @xref{Equality Predicates}.
1286 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1287 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1289 @result{} (pine . cones)
1292 On the other hand, @code{assq} is not usually useful in alists where the
1293 keys may not be symbols:
1297 '(("simple leaves" . oak)
1298 ("compound leaves" . horsechestnut)))
1300 (assq "simple leaves" leaves)
1302 (assoc "simple leaves" leaves)
1303 @result{} ("simple leaves" . oak)
1307 @defun rassq value alist
1308 This function returns the first association with value @var{value} in
1309 @var{alist}. It returns @code{nil} if no association in @var{alist} has
1310 a @sc{cdr} @code{eq} to @var{value}.
1312 @code{rassq} is like @code{assq} except that it compares the @sc{cdr} of
1313 each @var{alist} association instead of the @sc{car}. You can think of
1314 this as ``reverse @code{assq}'', finding the key for a given value.
1319 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1321 (rassq 'acorns trees)
1322 @result{} (oak . acorns)
1323 (rassq 'spores trees)
1327 Note that @code{rassq} cannot search for a value stored in the @sc{car}
1328 of the @sc{cdr} of an element:
1331 (setq colors '((rose red) (lily white) (buttercup yellow)))
1333 (rassq 'white colors)
1337 In this case, the @sc{cdr} of the association @code{(lily white)} is not
1338 the symbol @code{white}, but rather the list @code{(white)}. This
1339 becomes clearer if the association is written in dotted pair notation:
1342 (lily white) @equiv{} (lily . (white))
1346 @defun copy-alist alist
1347 @cindex copying alists
1348 This function returns a two-level deep copy of @var{alist}: it creates a
1349 new copy of each association, so that you can alter the associations of
1350 the new alist without changing the old one.
1354 (setq needles-per-cluster
1355 '((2 . ("Austrian Pine" "Red Pine"))
1357 (5 . "White Pine")))
1359 ((2 "Austrian Pine" "Red Pine")
1363 (setq copy (copy-alist needles-per-cluster))
1365 ((2 "Austrian Pine" "Red Pine")
1369 (eq needles-per-cluster copy)
1371 (equal needles-per-cluster copy)
1373 (eq (car needles-per-cluster) (car copy))
1375 (cdr (car (cdr needles-per-cluster)))
1376 @result{} "Pitch Pine"
1377 (eq (cdr (car (cdr needles-per-cluster)))
1378 (cdr (car (cdr copy))))