Lisp - List vs Vector



Lisp provides List and Vector as a data structures to store a collection of elements but both structures are having different characteristics and a suitablility varies as per the requirement. Following is the comparison.

List

  • Implementation− List is implemented as a single linked list where each node points to the next node.

  • Memory Storage− List is stored in non-contigous memory locations.

  • Access− List elements are accessed sequentially. List is to be traversed from beginning to access an element.

  • Insertion/Deletion− Insertion/Deletion from beginning is highly efficient.

  • Use cases− A list is useful when order is important and Insertion/Deletion operations are frequent.

Vector

  • Implementation− Vector is implemented as single dimensional array.

  • Memory Storage− Vector is stored in contigous memory locations.

  • Access− Random Access. Vector elements can be accessed randomly using their indexes.

  • Insertion/Deletion− Insertion/Deletion is less efficient as shifting elements may hamper performance.

  • Use cases− A vector is useful when random access is important and collection size is fixed.

List vs Vector

Following table summarizes the key differences.

Feature List Vector
Implementation Singly Linked List Array
Memory Storage Non-Contigous Contigous
Access Sequential Random Access
Insertion/Deletion Efficient Less Efficient
Use Cases Ordered collection, frequent insertion/deletion Fast random access, fixed size

Choosing List or Vector

  • List − When we need to maintain order of insertion in a collection and insertion/deletion operations are frequent especially at the beginning of the list.

  • Vector − When collection size is fixed and element are to accessed frequently by indexes.

Example - List

Following is an example of a List of numbers.

main.lisp

; define a list
(defvar myList '(1 2 3 4 5))
; print the list
(print myList)

Output

When you execute the code, it returns the following result −

(1 2 3 4 5)

Example - Vector

Following is an example of a vector of numbers.

main.lisp

; define a vector
(defvar myVector #(1 2 3 4 5))
; print the vector
(print myVector)

Output

When you execute the code, it returns the following result −

#(1 2 3 4 5)
Advertisements