Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 48 ยท Core Language

Tuples and Lists

Learn how Elixir tuples and linked lists work, how to use head and tail, what ++ and -- cost, and when keyword lists are the right choice.

Elixir has two everyday collections for ordered data: tuples and lists. They look similar, but they are built differently and used for different jobs. A tuple is a small, fixed-size group of values stored side by side. A list is a chain of cells, where each cell holds one value and points at the rest.

Knowing that difference explains Elixir's rules about speed (prepending is cheap, appending is not), and it tells you which one to pick when you design a function's return value. Because all data is immutable (see Immutability and Rebinding), every "change" here returns a new collection.

Tuple or list?

Tuple Fixed size, fast access by position.
List Linked cells, any length.

Tuples group a few things. Lists hold many things.

1 / 2

Tuples

A tuple is written with curly braces. It stores its elements next to each other in memory, so reading any element by position is fast, and getting its size is instant.

ELIXIR
point = {3, 4}
result = {:ok, "saved"}

elem(point, 0)          # 3
tuple_size(point)       # 2
put_elem(point, 1, 10)  # {3, 10}, a new tuple
point                   # {3, 4}, unchanged

Because a "change" copies the whole tuple, tuples are best when they are small and you rarely modify them. The most famous use is returning results from functions: {:ok, value} or {:error, reason}. You then take them apart with pattern matching (Pattern Matching: The = Operator):

ELIXIR
{:ok, message} = {:ok, "saved"}
message   # "saved"

Do not use a tuple for a long, growing sequence of items. That is a job for a list.

Lists are linked cells

A list is written with square brackets. Internally, [1, 2, 3] is a chain: a cell holding 1 that points to a cell holding 2 that points to a cell holding 3 that points to the empty list []. That structure is written in code with the cons operator |:

ELIXIR
[1, 2, 3] == [1 | [2 | [3 | []]]]   # true

The first cell's value is the head and everything after it is the tail:

ELIXIR
list = [10, 20, 30]

hd(list)         # 10
tl(list)         # [20, 30]
[head | tail] = list
head             # 10
tail             # [20, 30]

Both hd/1 and tl/1 raise an ArgumentError for an empty list, and so does [head | tail] = [] (it raises MatchError). Looking at the head and tail of a list is how Elixir code walks over lists, which you will do constantly once you reach Recursion and Tail Calls.

A string in double quotes is not a list. A charlist in single quotes is a list of integers. They are different types, covered in Strings and Binaries.

The cost of list operations

Since a list is a chain, some operations are quick and some are slow:

Operation Cost Why
[x | list] (prepend) constant one new cell pointing at the old list
hd/1, tl/1 constant the first cell is right there
length/1 proportional to length every cell is counted
Enum.at(list, i) proportional to i must walk from the front
list ++ other proportional to the left list the left cells are copied
List.last/1 proportional to length walk to the end

The practical rule: add to the front, not the back. If you build a list by prepending, you often reverse it once at the end:

ELIXIR
[0 | [1, 2, 3]]            # [0, 1, 2, 3], cheap
[1, 2, 3] ++ [4]           # [1, 2, 3, 4], copies three cells
Enum.reverse([3, 2, 1])    # [1, 2, 3]

Repeated list ++ [item] inside a loop turns a linear job into a quadratic one. Bad habits like this are collected in Performance and Common Pitfalls.

The -- operator removes the first occurrence of each element on the right: [1, 2, 3, 2] -- [2] gives [1, 3, 2]. Other useful functions are List.delete/2, List.first/1, List.flatten/1, Enum.member?/2 and List.insert_at/3. As always they return new lists.

Keyword lists

A keyword list is a list of two-element tuples whose first element is an atom. There is a shortcut syntax for it:

ELIXIR
options = [timeout: 5000, retries: 3]
options == [{:timeout, 5000}, {:retries, 3}]   # true

Keyword.get(options, :retries)     # 3
Keyword.get(options, :missing, 0)  # 0, default
options[:timeout]                  # 5000

Keyword lists keep their order, and the same key may appear more than once (Keyword.get/2 returns the first). Lookup walks the list, so they are meant for small option lists, such as the last argument of a function: String.split("a b", " ", trim: true). When a call's last argument is a keyword list, you can leave out the square brackets. For larger key-value data that you look up often, use a map, the topic of Maps and Structs.

A JavaScript stand-in for a linked list

This stand-in builds a linked list of cons cells to show why prepending shares the old list and why ++ copies the left side. Real Elixir lists live inside the BEAM virtual machine and are not JavaScript objects, so treat this as a model of the idea.

JS Cons cells and the cost of ++ (JavaScript stand-in)

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

No output.

Prepending made one cell and shared the rest. Appending one element to a three-element list made four cells: the three copied plus the new one.

The second stand-in imitates a keyword list with an array of pairs. Notice that duplicates are allowed and the first match wins.

JS A keyword list as pairs (JavaScript stand-in)

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. Which operation on a list is cheapest?

    Prepending creates one new cell that points at the existing list. The other operations must walk or copy cells.
  2. 2. What does [head | tail] = [5, 6, 7] bind to tail?

    head is the first element, 5. tail is a list of everything after it, [6, 7].
  3. 3. What is [1, 2, 3, 2] -- [2]?

    -- removes only the first occurrence of each element listed on the right.
  4. 4. When is a tuple a better fit than a list?

    Tuples are compact and fixed size, which suits result pairs and small records. Lists suit collections of varying length.
  5. 5. What is [a: 1, b: 2]?

    It is a keyword list, shorthand for [{:a, 1}, {:b, 2}].

Summary

  • Tuples are fixed-size groups with fast access by position; they are ideal for results like {:ok, value}.
  • Lists are linked cells made of a head and a tail, written [head | tail].
  • Prepending is cheap; ++, length/1 and indexing cost time proportional to list length.
  • -- removes the first occurrence of each element on the right.
  • Keyword lists are lists of {atom, value} pairs, good for small option lists, and may repeat keys.
  • Every function returns a new collection and never changes the original.

Next up: Maps and Structs.