Elisp: Filter a List

By Xah Lee. Date: . Last updated: .

How to filter elements in a list?

emacs 25.1 or later:

use seq-filter in package (require 'seq)

[see Elisp: Sequence Functions]

(require 'seq)

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

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

;; old remain unchanged
;; '(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://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)

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

see also Elisp: String Match in List

Elisp Data Structure

  1. List
  2. Vector
  3. Sequence: List, Array
  4. Sequence Functions
  5. Map List/Vector
  6. Exit Loop/Function
  7. Association List
  8. Property List
  9. Symbol Property List
  10. Hash Table

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp