Elixir Lists & Tuples
Elixir has two basic ordered collections. They look similar but are stored very differently, and that difference decides which one to use.
List [1, 2, 3] |
Tuple {1, 2, 3} |
|
|---|---|---|
| Storage | linked list (each element points to the next) | one contiguous block of memory |
| Length | length/1, walks the list: O(n) |
tuple_size/1: O(1) |
| Read element i | O(i) | O(1) with elem/2 |
| Add at the front | cheap: [new | list] |
copies the whole tuple |
| Typical use | sequences of any length you iterate over | a fixed number of fields, return values |
Lists
langs = ["Elixir", "Erlang", "Gleam"]
IO.inspect(length(langs))
IO.inspect(hd(langs))
IO.inspect(tl(langs))
IO.inspect(["LFE" | langs]) # prepend: fast
IO.inspect(langs ++ ["Lua"]) # append: copies langs
IO.inspect(Enum.at(langs, 1))
IO.inspect(List.last(langs))
IO.inspect("Gleam" in langs)3
"Elixir"
["Erlang", "Gleam"]
["LFE", "Elixir", "Erlang", "Gleam"]
["Elixir", "Erlang", "Gleam", "Lua"]
"Erlang"
"Gleam"
true
hd/1 and tl/1 return the head (first element) and tail (the rest). Prepending with [x | list] doesn't copy anything: the new list just points to the old one, which is safe because lists are immutable. That is why idiomatic Elixir builds lists by prepending and calls Enum.reverse/1 once at the end.
The structure of a list
A list is either empty [] or a head plus a tail list. [1, 2, 3] is just sugar for [1 | [2 | [3 | []]]]:
IO.inspect([1 | [2 | [3 | []]]])
IO.inspect([1 | [2 | [3 | []]]] == [1, 2, 3])
IO.inspect(List.flatten([1, [2, [3, 4]], 5]))
IO.inspect(List.delete([:a, :b, :a], :a))
IO.inspect(List.duplicate("-", 3))
IO.inspect(Enum.zip([:x, :y], [10, 20]))[1, 2, 3]
true
[1, 2, 3, 4, 5]
[:b, :a]
["-", "-", "-"]
[x: 10, y: 20]
Tuples
Tuples group a fixed number of values. They are the standard way to return a result together with a status:
point = {3, 4}
IO.inspect(elem(point, 0))
IO.inspect(tuple_size(point))
moved = put_elem(point, 1, 10)
IO.inspect(moved)
IO.inspect(point) # unchanged
{x, y} = point
IO.inspect(:math.sqrt(x * x + y * y))3
2
{3, 10}
{3, 4}
5.0
put_elem/3 returns a new tuple; the original point is unchanged.
Tagged tuples: {:ok, value} and {:error, reason}
Many functions in the standard library return a tuple whose first element is an atom tag. Integer.parse/1, File.read/1 and Map.fetch/2 are examples:
IO.inspect(Integer.parse("42 apples"))
IO.inspect(Integer.parse("apples"))
IO.inspect(Map.fetch(%{a: 1}, :a))
IO.inspect(Map.fetch(%{a: 1}, :b))
IO.inspect(File.read("/no/such/file")){42, " apples"}
:error
{:ok, 1}
:error
{:error, :enoent}
The caller then uses pattern matching (case, with) to handle each outcome. You will write your own functions in this style throughout the course.
Choosing between them
- A collection of things you will loop over, filter or map: list.
- A small group of values with fixed meaning by position, such as
{latitude, longitude}or{:ok, result}: tuple. - Values with names: a map or struct (later lessons), because
{"Ada", 36, "London"}doesn't say what each field means.
Note: Enumerating functions such as
Enum.map/2work on lists but not on tuples. Tuples are not meant to be iterated; convert withTuple.to_list/1if you really need to.
Common mistakes
- Using
list[0]: lists have no index syntax. UseEnum.at(list, 0)or pattern matching, and remember that indexed access is O(n). - Appending in a loop with
list ++ [x]: each append copies the list, which makes the loop O(n²). Prepend and reverse instead. - Calling
length(list) == 0to check emptiness: compare with[]or match[]directly.
Test yourself
Which operation is cheap on a list?
- Reading the last element
- Appending with
++ [x] - Prepending with
[x | list] length/1
What does put_elem({1, 2}, 0, :a) return?
{:a, 2}and the original tuple is unchanged:ok, and the tuple becomes{:a, 2}{1, :a}- An error, tuples are immutable
What is Integer.parse("12kg")?
12{12, "kg"}{:ok, 12}:error