🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Lists

A list is an ordered collection of values written in square brackets. A list can grow or shrink, and new lists are built from old ones.

The head and tail pattern splits a list

The [head | tail] pattern takes a list apart. The head is the first value and the tail is the list that remains.

numbers = [150, 200, 250]
[head | tail] = numbers
IO.puts(head)
IO.inspect(tail)

hd, tl, length, and in read a list

The hd and tl functions split a list without a pattern. The length and in operators answer questions about the whole list.

words = ["red", "green", "blue"]
IO.puts(hd(words))
IO.inspect(tl(words))
IO.puts(length(words))
IO.inspect("green" in words)

Lists join, shrink, and flatten

The ++ operator joins lists and the -- operator removes values. The List module reads the ends of a list and flattens nested lists.

first_part = [200, 300]
second_part = [400, 500]
joined = first_part ++ second_part
IO.inspect(joined)
IO.inspect(joined -- [300])
IO.inspect(List.first(joined))
IO.inspect(List.last(joined))
IO.inspect(List.flatten([[200, 300], [400]]))

Example

cart = [150, 250]
full_cart = cart ++ [350]
[head | rest] = full_cart
IO.puts(head)
IO.inspect(rest)
IO.puts(length(full_cart))
IO.inspect(250 in full_cart)
IO.inspect(List.flatten([[150], [250, 350]]))

Key points

  • List literal: Square brackets hold the values in order, such as [150, 200, 250].
  • Head and tail: The pattern [head | tail] splits a list into its first value and the rest.
  • hd and tl: Use hd(list) for the first value and tl(list) for the rest of the list.
  • length: Use length(list) to count the values in a list.
  • Join and remove: The ++ operator joins two lists and the -- operator removes values from a list.
  • Membership: The in operator checks whether a value is in a list and returns true or false.

In this example, the ++ operator joins 350 onto the cart to make a three-value list. The head and tail pattern then splits that list into 150 and the remaining two values. The last lines count the values, confirm that 250 is in the list, and flatten two small lists into one.

Note

List functions return new lists, so the original list is never changed in place.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the value of hd([150, 200, 250])?