Elisp: Sequence. Sort, Reverse

By Xah Lee. Date: . Last updated: .

sort

sort

(sort SEQ &key KEY LESSP REVERSE IN-PLACE)

major change in Emacs 30 (date 2025)

  • sort a List or Vector
  • Stable sort.
  • Return the sorted sequence.
  • Original not changed. (by default)

Optional arguments are keyword argument pairs.

  • :key FUNCFUNC is a function. It is given one element from SEQ. Return value is used for comparison. If nil, identity is used.
  • :lessp FUNCFUNC is a function that takes two args and returns true if they are in order. If nil, value< is used.
  • :reverse BOOL → if BOOL is true, the sorting order implied by FUNC is reversed.
  • :in-place BOOL → if BOOL is true, SEQ is sorted in-place and returned. Default is false.

For compatibility, the calling convention (sort SEQ LESSP) can also be used; in this case, sorting is always done in-place.

(setq xx (list 2 3 1))
(sort xx )
;; (1 2 3)
(setq xx (vector ["b" 1] ["c" 3] ["a" 2]))

;; sort by second column
(sort xx :key (lambda (x) (aref x 1)))
;; [["b" 1] ["a" 2] ["c" 3]]

;; sort normally, by first column
(sort xx )
;; [["a" 2] ["b" 1] ["c" 3]]

before emacs 30:

(sort SEQ PREDICATE)

(setq xx (list 2 4 1 9 5))

(sort xx '>)
;; (9 5 4 2 1)

xx
;; (9 5 4 2 1)

;; note, the original list may be destroyed
seq-sort

(seq-sort PRED SEQUENCE)

(setq xx (list 2 4 1 9 5))

(seq-sort '> xx)
;; (9 5 4 2 1)

xx
;; (2 4 1 9 5)
;; original unchanged
seq-sort-by

(seq-sort-by FUNCTION PRED SEQUENCE)

Sort sequence, by the value of a function applied to each element.

FUNCTION takes one arg.

(setq xx (list "a-9" "b-3" "c-2" ))

;; sort by the number in the string
(seq-sort-by
 (lambda (x) (string-to-number (substring x 2)))
 '<
 xx)
;; ("c-2" "b-3" "a-9")

xx
;; ("a-9" "b-3" "c-2")

Reverse

;; example showing how nreverse destroys the original value

(setq xx (number-sequence 1 5))
(setq yy (nreverse xx))

xx
;; (1)

yy
;; (5 4 3 2 1)

Emacs Lisp, sequence functions