Emacs Lisp: Vector

By Xah Lee. Date: . Last updated: .

Emacs lisp vector datatype is a ordered sequence of values, with fixed number of elements.

Create Vector

(make-vector length val)
Create a vector of given length and value for all elements.
(make-vector 5 0) ;; [0 0 0 0 0]
(vector a b etc)
Create a vector with elements, the elements are evaluated.
(setq x (vector 3 4.2 "abc"))
(setq x 7)
(setq v (vector 3 x 5))
v ; [3 7 5]
[a b etc]
Create a vector, do not evaluate elements.
(setq n 7)
(setq v [3 n 5])
v ; [3 n 5]
;; the n remains a symbol, not 7

Fill Vector

(fillarray array val)
Make all elements of array to have value val .
(setq aa [3 4 5])
(fillarray aa nil) ;; [nil nil nil]

Length

(length (vector 7 4 5)) ; 3

Get Element

(aref array n)
Return the element of array at index n.
(elt sequence n)
Return element of sequence at index n.

When emacs doc mentions “ARRAY”, you can think of it as “vector or string”.

When emacs doc mentions “SEQUENCE”, you can think of it as “list or array”.

;; get a element from vector
(aref ["a" "b" "c"] 0) ; "a"
;; get a element from vector
(elt ["a" "b" "c"] 0) ; "a"

What is the difference between aref and elt?

elt is more general. It works on vector and list. But if you know it's vector, you should use aref, because it's precise and faster. [see Emacs Lisp: Sequence Type]

Change Element

(aset ARRAY IDX NEWELT)
Store into the element of ARRAY at index IDX the value NEWELT. Return NEWELT.
(setq v [3 4 5])
(aset v 0 "b")
v  ; ["b" 4 5]

Nested Vector

Vector can be nested in any way, because the elements can be any type.

;; nested vector
[[1 2] [3 4]] ; 2 by 2 matrix
;; random nested vector
[8 [3 [2 9] c] 7 [4 "b"]]

Join Vectors, Convert List to Vector

(vconcat sequence1 sequence2 etc)
Join any sequence types and return a vector. (List and vector are both sequence types.)
;; join any sequence types
(vconcat [3 4] ["a" "b"]) ; [3 4 "a" "b"]

(vconcat [3 4] '("a" "b")) ; [3 4 "a" "b"]

(vconcat [3 4] "ab") ; [3 4 97 98]
;; string elements are converted to char.
;; 97 is the codepoint for the char a

Convert Vector to List

(append sequence1 sequence2 etc)
Join any sequence types and return a list. (List and vector are both sequence types.)
Warning: if you want it to return a proper list, the last element must be a list, or nil.
;; convert vector to list
(append [1 2 3] nil)
; (1 2 3)

(append [1 2 3] [4 5] )
;; (1 2 3 . [4 5])
;; this is improper list

(append [1 2 3] [4 5] nil)
;; (1 2 3 4 5)
;; proper list

(append [1 2 3] [4 5] '(6))
;; (1 2 3 4 5 6)
;; proper list

Reference

(info "(elisp) Vectors")

(info "(elisp) Vector Functions")

Lisp Basics

Lisp Data Structure

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp