Skip to content
Lists and Tuples
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Lists are linked lists — head/tail. Prepending is O(1); appending or random access is O(n). Use them for sequential processing.

nums = [1, 2, 3, 4]
IO.puts hd(nums)        # 1 — head
IO.inspect tl(nums)     # [2, 3, 4] — tail
IO.inspect [0 | nums]   # [0, 1, 2, 3, 4] — prepend (O(1))
IO.inspect nums ++ [5]   # [1, 2, 3, 4, 5] — concat (O(length of left))
IO.puts length(nums)     # 4 (O(n) — no cached length)

Tuples are fixed-size groupings — heterogeneous, indexed, used for return values and small structured data:

result = {:ok, "some value"}
{status, value} = result   # destructure
IO.puts elem({1, 2, 3}, 0) # 1

Tuples are random-access (O(1)) but resizing creates a new tuple. Don't use them as growing collections — that's what lists or maps are for.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Lists and Tuples — Elixir Fundamentals