Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Data Structures

Lists and Vectors in Clojure

Understand Clojure's ordered collections: linked lists and indexed vectors, how conj behaves differently, nth, assoc, subvec, peek and pop, and which one to choose for your data.

Clojure has four core collections: lists, vectors, maps and sets. They are all immutable and share a common set of functions such as count, first, conj and seq. This lesson covers the two ordered ones: lists and vectors. In practice you will use vectors much more often.

Vectors

A vector is an indexed, ordered collection written with square brackets. Looking up an element by position is fast.

CLOJURE
[1 2 3]
["a" :b 3.5 nil]       ; elements can be of different types
(vector 1 2 3)         ; [1 2 3]
(vec '(1 2 3))         ; [1 2 3]  convert another collection
(vec (range 5))        ; [0 1 2 3 4]

Reading from a vector

CLOJURE
(def v [10 20 30 40])

(get v 1)       ; 20
(nth v 2)       ; 30
(v 0)           ; 10     a vector is itself a function of the index
(get v 9)       ; nil    out of range: nil
(nth v 9)       ; throws IndexOutOfBoundsException
(nth v 9 :none) ; :none  with a default
(first v)       ; 10
(last v)        ; 40
(count v)       ; 4
(peek v)        ; 40     the last element: fast for vectors
(subvec v 1 3)  ; [20 30]   a cheap slice

get is forgiving and returns nil for a missing index; nth throws unless you give it a default. Choose according to whether a missing element is an error.

"Changing" a vector

Because vectors are immutable, each operation returns a new vector and leaves the old one unchanged:

CLOJURE
(conj v 50)         ; [10 20 30 40 50]   adds to the END
(assoc v 1 99)      ; [10 99 30 40]      replaces index 1
(assoc v 4 50)      ; [10 20 30 40 50]   index = count is allowed
(pop v)             ; [10 20 30]         removes the last element
(into v [1 2])      ; [10 20 30 40 1 2]  adds many
(concat v [1 2])    ; (10 20 30 40 1 2)  a lazy sequence, not a vector
(update v 0 inc)    ; [11 20 30 40]      apply a function to one element
v                   ; [10 20 30 40]      still the original

conj always adds in the cheapest place for the collection. For vectors this is the end.

JS Stand-in: vector operations returning new arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that JavaScript copies the whole array each time here. Clojure's real vectors avoid copying by sharing most of their structure, as explained in Immutability and Persistent Data.

Lists

A list is a singly linked list written with parentheses. Because an unquoted list is a function call, a literal list needs a quote or the list function:

CLOJURE
'(1 2 3)
(list 1 2 3)
(list)           ; ()  the empty list

Lists are efficient at the front, so conj adds there:

CLOJURE
(conj '(2 3) 1)     ; (1 2 3)
(first '(1 2 3))    ; 1
(rest '(1 2 3))     ; (2 3)
(peek '(1 2 3))     ; 1      the front
(pop '(1 2 3))      ; (2 3)
(nth '(1 2 3) 2)    ; 3      works, but walks the list: slow for long lists

You can see the difference at once:

CLOJURE
(conj [1 2 3] 4)    ; [1 2 3 4]
(conj '(1 2 3) 4)   ; (4 1 2 3)

Lists have no fast indexed access, and count is stored so it is fast, but nth is linear. For this reason, most data in Clojure programs lives in vectors, and lists are mainly used to represent code, as in (+ 1 2), and for stack-like behaviour at the front.

Vector or list?

Vector Indexed. conj adds at the end.
List Linked. conj adds at the front.
Default choice Use a vector for data.
Lists as code Macros build and read lists.

Both are immutable and print differently.

1 / 2

The common sequence functions

Both collections work with all sequence functions:

CLOJURE
(map inc [1 2 3])            ; (2 3 4)    note: returns a lazy seq, not a vector
(mapv inc [1 2 3])           ; [2 3 4]    mapv returns a vector
(filter odd? [1 2 3 4 5])    ; (1 3 5)
(filterv odd? [1 2 3 4 5])   ; [1 3 5]
(reduce + [1 2 3 4])         ; 10
(take 2 [10 20 30])          ; (10 20)
(drop 2 [10 20 30])          ; (30)
(reverse [1 2 3])            ; (3 2 1)
(sort [3 1 2])               ; (1 2 3)
(sort-by count ["ccc" "a" "bb"])   ; ("a" "bb" "ccc")
(distinct [1 2 1 3 2])       ; (1 2 3)
(partition 2 [1 2 3 4 5])    ; ((1 2) (3 4))
(partition-all 2 [1 2 3 4 5]) ; ((1 2) (3 4) (5))
(interleave [1 2] [:a :b])   ; (1 :a 2 :b)
(zipmap [:a :b] [1 2])       ; {:a 1, :b 2}

Many sequence functions return a lazy sequence even when you give them a vector. When you need a vector (for fast indexing or conj at the end), use mapv, filterv, into [] or vec.

Equality across collections

Collections are equal when they have the same elements in the same order, regardless of whether they are a list or a vector:

CLOJURE
(= [1 2 3] '(1 2 3))   ; true
(= [1 2 3] [3 2 1])    ; false
(identical? [1] [1])   ; false (different objects)

This lets you swap a list for a vector without breaking comparisons in tests.

A stack and a queue

Vectors and lists naturally act as stacks with conj, peek and pop:

CLOJURE
(def stack [])
(def stack (conj stack :a))     ; push
(def stack (conj stack :b))
(peek stack)                    ; :b   look at the top
(pop stack)                     ; [:a] remove the top

For a FIFO queue, Clojure offers clojure.lang.PersistentQueue/EMPTY (conj to the back, peek and pop from the front). It has no literal syntax, so you rarely meet it outside concurrency code.

JS Stand-in: using an array as a stack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (conj [1 2 3] 4) return?

    For vectors conj adds at the end and keeps the vector type.
  2. 2. What does (conj '(1 2 3) 4) return?

    For lists conj adds at the front, the cheapest place.
  3. 3. What is the difference between get and nth for an out-of-range index?

    get is lenient and returns nil; nth throws IndexOutOfBoundsException unless you pass a default.
  4. 4. What does (= [1 2 3] '(1 2 3)) return?

    Lists and vectors with equal elements in the same order are equal.
  5. 5. Which function gives you a vector result from mapping?

    mapv is like map but returns a vector.

Summary

  • Vectors ([...]) are indexed and grow at the end; lists ('(...)) are linked and grow at the front.
  • Use get, nth, peek, subvec to read; conj, assoc, pop, into, update to produce new vectors.
  • Most sequence functions return lazy sequences; use mapv, filterv or vec for vectors.
  • Lists and vectors with the same elements are equal.
  • Prefer vectors for data, lists for code.

Next: Maps and Keywords as Functions