Elisp: Filter a List

By Xah Lee. Date: . Last updated: .

How to filter elements in a list?

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

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://ergoemacs.org/emacs/elisp_filter_list.html'
Version 2016-07-18"
    (lambda ($x)
      (if (funcall @predicate $x)
        "e3824ad41f2ec1ed" ))
;; test
(setq xx '(1 "a" 2))

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

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

for many functions that check if a element exists or filter a list/sequence, see: (info "(elisp) Sets And Lists")

Thanks to Artur Malabarba, Matthew Fidler.

see also Elisp: String Match in List

Data Structure Topic

  1. Elisp: Sequence: List, Array
  2. Elisp: Vector
  3. Elisp: List
  4. Elisp: Association List
  5. Elisp: Property List
  6. Elisp: Symbol Property List
  7. Elisp: Map / Loop Thru List / Vector
  8. Elisp: Filter a List
  9. Elisp: Hash Table
Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.