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)

(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)

Emacs 25.1 Sequence Functions

emacs 25.1 added over 10 functions on sequences. They work on list, vector, string.

  1. sequencep
  2. length
  3. elt
  4. copy-sequence
  5. reverse
  6. nreverse
  7. sort
  8. seq-elt
  9. seq-length
  10. seqp
  11. seq-drop
  12. seq-take
  13. seq-take-while
  14. seq-drop-while
  15. seq-do
  16. seq-map
  17. seq-mapn
  18. seq-filter
  19. seq-remove
  20. seq-reduce
  21. seq-some
  22. seq-find
  23. seq-every-p
  24. seq-empty-p
  25. seq-count
  26. seq-sort
  27. seq-contains
  28. seq-position
  29. seq-uniq
  30. seq-subseq
  31. seq-concatenate
  32. seq-mapcat
  33. seq-partition
  34. seq-intersection
  35. seq-difference
  36. seq-group-by
  37. seq-into
  38. seq-min
  39. seq-max
  40. seq-doseq
  41. seq-let

(info "(elisp) Sequence Functions")

See also: (info "(elisp) Sets And Lists")

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"
  (delete
   "e3824ad41f2ec1ed"
   (mapcar
    (lambda ($x)
      (if (funcall @predicate $x)
          $x
        "e3824ad41f2ec1ed" ))
    @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 [https://github.com/Malabarba], • Matthew Fidler [https://github.com/mattfidler]

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
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.