Emacs Lisp: Filter a List

By Xah Lee. Date: . Last updated: .

How to filter elements in a list?

use seq-filter in package (require 'seq) [see Emacs Lisp: Sequence Functions] (emacs 25.1 or later)

(require 'seq)

(setq xx '(1 "a" 2))

;; remove items that's not a number
(seq-filter 'numberp xx)
;; (1 2)

;; old remain unchanged
xx
;; '(1 "a" 2)

Before emacs 25, use cl-remove-if

You can use the cl-remove-if or cl-remove-if-not in CL library, like this:

(require 'cl-lib)
(cl-remove-if-not 'numberp  '(1 "a" 2)) ;; (1 2)

Note: emacs 24.x renamed remove-if to cl-remove-if

Write Your Own

If you want to avoid the controversial CL lib, you can write your own:

(defun xah-filter-list (Predicate Sequence)
  "Return a new list such that Predicate is true on all members of Sequence.

URL `http://xahlee.info/emacs/emacs/elisp_filter_list.html'
Version 2016-07-18 2021-09-17"
  (delete 11571956437633
          (mapcar
           (lambda ($x)
             (if (funcall Predicate $x)
                 $x
               11571956437633
               ))
           Sequence)))
;; test
(setq xx '(1 "a" 2))

;; returns a new list
(xah-filter-list 'numberp xx) ; (1 2)

;; old remain unchanged
xx ; '(1 "a" 2)

Thanks to • Artur Malabarba [[2017-11-20 https://github.com/Malabarba ]], • Matthew Fidler [[2017-11-20 https://github.com/mattfidler ]]

Emacs Lisp: Filter List