Function: alist-get

alist-get is a byte-compiled function defined in subr.el.gz.

Signature

(alist-get KEY ALIST &optional DEFAULT REMOVE TESTFN)

Documentation

Find the first element of ALIST whose car equals KEY and return its cdr.

If KEY is not found in ALIST, return DEFAULT. Equality with KEY is tested by TESTFN, defaulting to eq.

You can use alist-get in "place expressions"; i.e., as a generalized variable. Doing this will modify an existing association (more precisely, the first one if multiple exist), or add a new element to the beginning of ALIST, destructively modifying the list stored in ALIST.

Example:

   (setq foo '((a . 0)))
   (setf (alist-get 'a foo) 1
         (alist-get 'b foo) 2)

   foo => ((b . 2) (a . 1))


When using it to set a value, optional argument REMOVE non-nil means to remove KEY from ALIST if the new value is eql to DEFAULT (more precisely the first found association will be deleted from the alist).

Example:

  (setq foo '((a . 1) (b . 2)))
  (setf (alist-get 'b foo nil 'remove) nil)

  foo => ((a . 1))

Other relevant functions are documented in the list and alist groups.

View in manual

Probably introduced at or before Emacs version 25.1.

Shortdoc

;; alist
(let ((foo '((bar . baz)))) (setf (alist-get 'bar foo) 'zot) foo)
    => ((bar . zot))
;; list
(alist-get 2 '((1 . a) (2 . b)))
    => b

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun alist-get (key alist &optional default remove testfn)
  "Find the first element of ALIST whose `car' equals KEY and return its `cdr'.
If KEY is not found in ALIST, return DEFAULT.
Equality with KEY is tested by TESTFN, defaulting to `eq'.

You can use `alist-get' in \"place expressions\"; i.e., as a
generalized variable.  Doing this will modify an existing
association (more precisely, the first one if multiple exist), or
add a new element to the beginning of ALIST, destructively
modifying the list stored in ALIST.

Example:

   (setq foo \\='((a . 0)))
   (setf (alist-get \\='a foo) 1
         (alist-get \\='b foo) 2)

   foo => ((b . 2) (a . 1))


When using it to set a value, optional argument REMOVE non-nil
means to remove KEY from ALIST if the new value is `eql' to
DEFAULT (more precisely the first found association will be
deleted from the alist).

Example:

  (setq foo \\='((a . 1) (b . 2)))
  (setf (alist-get \\='b foo nil \\='remove) nil)

  foo => ((a . 1))"
  (ignore remove) ;;Silence byte-compiler.
  (let ((x (if (not testfn)
               (assq key alist)
             (assoc key alist testfn))))
    (if x (cdr x) default)))