Published 3 min readElixir

A List Is Not an Array

Elixir lists look like arrays, but they are linked lists. Here's what that changes: head, tail and recursion.

Linked lists, not arrays

Coming from Ruby, where arrays let you access elements by index, it is easy to read [1, 2, 3] in Elixir as an array. It is a linked list: each item points to the next one.

A list has a head (its first item) and a tail (the rest of the list). You can get them with hd/1 and tl/1, or with pattern matching.

iex
list = [1, 2, 3]

hd(list) # => 1
tl(list) # => [2, 3]

[head | tail] = list
# head => 1, tail => [2, 3]

Iterating with recursion

Iterating over a list is done recursively, with a base case for the empty list; Elixir's own List functions work the same way under the hood. The List module also offers helpers such as first/1, last/1 and insert_at/3.

All articles