Unpacking Values from Lists, Maps, and Structs

Explore pattern matching with lists, maps, and structs.

Matching lists

Tuples represent collections of a few items. We’ve used pattern matching on them, taken values, and put them in variables. But tuples have one limitation: they’re stored contiguously in memory. We need to know in advance how many elements are inside of them. It’s a problem because we can’t always predict a collection size, and it’s impractical to write all the items of a vast collection in an expression. To address these problems, Elixir uses the list data type. In Elixir, lists are linked lists. That means each item of the collection contains a value and an implicit reference to the next element. For a list [:a, :b, :c, :d, :e], we’ll have something like this in memory:

Get hands-on with 1400+ tech skills courses.