liveBook · Manning

Tuple

As explained in Elixir in Action, Third Edition

A tuple is an Elixir data structure containing a fixed number of terms in positional order.

A tuple groups a small, fixed number of terms in positional order. It suits record-like values whose fields are known ahead of time; use a list for a dynamically sized collection. section 2.4.3 section 2.8

Work with tuple fields through positional operations:

  • Create a tuple such as {"Bob", 25}. section 2.4.3
  • Read a field with elem(tuple, index); indexes are zero-based. section 2.4.3
  • Update a field with put_elem(tuple, index, value), which returns a new tuple rather than modifying the old one. section 2.4.3 section 2.4.5

Rebinding an updated tuple

person = {"Bob", 25} older_person = put_elem(person, 1, 26) person remains {"Bob", 25}, while older_person contains {"Bob", 26}. Rebinding person to the returned value is also valid. Updating creates a complete shallow copy; nested values are shared where possible. section 2.4.3 section 2.4.5

How Elixir in Action, Third Edition covers it

How deep it goes
Explains construction, zero-based access, immutable updates, shallow copying, and the boundary with dynamically sized lists.
Examples
Uses a person tuple, elem/2, put_elem/3, rebinding, and a shallow-copy illustration.
What you can do after
Apply it via elem/2 and put_elem/3 while preserving the original value through rebinding.
How it connects
Connects tuples to immutability, variable rebinding, shallow copying, garbage collection, and lists.

Also explained in

Compare how 15 books explain tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.