Elisp: List
What is List
Emacs Lisp's list datatype is an ordered sequence of things. It is known as linked list data structure in computer science. It is an efficient datatype for stack data structure. (like a stack of books, allowing adding or removing one item at a time from the top in an efficient way.)
Any item can be of any type.
Algorithm properties of lisp list:
- Fast and constant time to get value of first element. (by
car
) - Fast and constant time to get rest of list (i.e. without first item). (by
cdr
) - Fast and constant time to add one item to the beginning of list. (by
push
) - Fast and constant time to remove the first element. (by
pop
)
- Any operation for nth element, the larger n, the longer it takes.
- The longer the list, the longer it takes to find length, or search items.
Note: List is made up of lower structure called cons cells. 〔see Elisp: Cons Cell〕
Empty List, nil
In elisp, empty list is equivalent to nil
. The following are all equivalent.
'()
(list)
nil
(eq nil '()) ; t (eq nil (list)) ; t
Length
length
-
(length SEQUENCE)
return count of elements.
(length '(3 4)) ;; 2
length=
-
(length= SEQUENCE N)
return true if length is equal to N.
new in Emacs 28 (date 2022)
💡 TIP: this is more efficient than getting the length then do compare, especially when used on list with lots items. Because to get the length of list, the time is proportional to number of items.
length>
-
(length> SEQUENCE N)
return true if length is greater than N.
length<
-
(length< SEQUENCE N)
return true if length is less than N.