Elisp: Association List

By Xah Lee. Date: . Last updated: .

Association List (aka alist) is a value type in Emacs Lisp.

Association List is a List , where each element is a cons pair, like this (cons key value).

Note: (cons a b) can also be written as (a . b).

In each cons pair, the key and value can be any value type.

Items in Association List can have duplicate keys, and order is maintained.

If you have more than a thousand items, and need fast random access, better is to use Hash Table .

What's the Difference Between Association List and Hash Table?

Create a AList

(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

Get Pair by Key

assoc
(assoc key alist)
Return the first found pair with the key. If key do not exist, return nil. (key existence is checked by equal.)
(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

;; get the pair with key "john"
(assoc "john" x)
; returns ("john" . 24)

After you got the cons pair, you can use car to get the first element, and use cdr to get the last element.

(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

;; get the value with key "john"
(cdr (assoc "john" x))
; returns 24

Get Pair by Value

You can search alist by value.

rassq
(rassq value alist)
Return the first association with value value in alist. It returns nil if no association in alist has a CDR eq to value.
(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

;; get the pair with value 24
(rassoc 24 x)
; returns ("john" . 24)

More Alist Functions

Note, Association List is a List , any function that works on list also works on Association List.

[see Elisp: Sequence Functions]

There are many more specialized function for alist. See

(info "(elisp) Association Lists")

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp

Basics

Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc