Emacs Lisp: Create List

By Xah Lee. Date: . Last updated: .

Create List (Literal Expression)

To create a list, write it like this (list a b etc).

list
(list args)

create a list of items.

; assign a list to a var
(setq xx (list 1 "b" 3))
; prints a list
(message "%S" xx)

If you do not want the elements evaluated, write it like this:

'(a b etc)

This is equivalent to

(quote (a b etc))

; assign a list to a var
(setq xx '(a b c))

; prints a list
(message "%S" xx)
;; create a list of values of variables
(let (x y z)
  (setq x 3)
  (setq y 4)
  (setq z 5)
  (message "%S" (list x y z)))
 ;; "(3 4 5)"

[see Emacs Lisp: Test Equality]

Create List of Same Value

make-list
(make-list LENGTH INIT)

Create a list of length LENGTH, and all elements with value INIT.

(equal (make-list 3 0) '(0 0 0))

Create List of Range of Numbers

number-sequence
  • (number-sequence val)
  • (number-sequence n m)
  • (number-sequence n m step)

Return a list of 1 element of value val.

or

Return a list of a range of numbers, from n to m, in increment of step.

;; just 1 element
(equal
 (number-sequence 5)
 '(5))

;; n to m, inclusive
(equal
 (number-sequence 2 5)
 '(2 3 4 5))

;; using 3 as step
(equal
 (number-sequence 0 9 3)
 '(0 3 6 9))

(equal
 (number-sequence 0 9 2)
 '(0 2 4 6 8))
;; ending item dropped

;; negative step
(equal
 (number-sequence 4 0 -1)
 '(4 3 2 1 0))

;; boundaries can be float but will not include
(equal
 (number-sequence 2.2 5.3)
 '(2.2 3.2 4.2 5.2))

Reference

Lisp Data Structure

List

Specialized Lists

Vector

Sequence (List, Vector)

Hash Table