/ erlang

Erlang Data Structures : Tuples

  • It is a composite/compound data type.
  • We use {} curly braces to define a tuple.
  • Each item in a tuple is called element.
  • Elements are separated by ,
  • Elements need not be of same type.
  • Number of elements in tuple is its size.
  • A tuple can be of size zero if it have no elements => {}
  • Index starts from 1.

A person's details can be represented using Tuple as :


The first element is an atom with value person. Then we have first_name, last_name and age.

Tagged Tuple

A tuple with an atom as first element is called a Tagged Tuple and its a good practice to use them as they clearly state what the tuple represent. In the previos example we can see from the tag its a tuple regarding a person.

Destructure values to variables

We can use pattern matching to destructure the above tuple to unbound variables.


Here Fname, Sname, Age are now bound to "John","Doe" and 28 respectively.

Operations on Tuples

These are BIF in Erlang to work with Tuples.


Will return the element at index from Tuple.

1> T={laptop,"Dell","Inspiron","i7","16GB"}.
2> element(1,T).
3> element(2,T).


Replace element at index with Value and return a new tuple.

2>setelement(3,T,"Inspiron 15").
{laptop,"Dell","Inspiron 15","i7","16GB"}


Will return the size of the tuple.

1> T={laptop,"Dell","Inspiron","i7","16GB"}.
2> tuple_size(T).


Will return the atom true if this is a tuple else false.


Will convert a List to Tuple.

1> L=["Apple","Macbook Pro","15 Inch Retina"].
["Apple","Macbook Pro","15 Inch Retina"]
2> T=list_to_tuple(L).
{"Apple","Macbook Pro","15 Inch Retina"}


Will convert a Tuple to List.


erlang:delete_element(Index, Tuple)

Will delete the element at Index from tuple and return a new tuple.

Some BIFs are autoimported and hence we need not prefix the call with the module name. By convention most BIFs are in a module with name erlang. Eg:delete_element() is not auto-imported hence we prifix it with the module name.

2> erlang:delete_element(3,T).

erlang:insert_element(Index, Tuple, Term)

Will insert Term at Index and return a new tuple.

2> erlang:insert_element(4,T,"Intel").  

erlang:append_element(Tuple, Term)

This will append the Term to the end of Tuple and will return a new tuple.

2> erlang:append_element(T,"1TB SSD").
{laptop,"Dell","Inspiron","i7","16GB","1TB SSD"}


Erlang Docs
Erlang Programming Book