Erlang Central

Extracting a Sublist

From ErlangCentral Wiki

Problem

Given a list, extract a segment specified by a start index and an optional length.

Solution

Use the lists:sublist/2 or lists:sublist/3 functions. The lists:sublist/2 function takes the first N elements from a list, while the lists:sublist/3 function takes a starting point in the list and the maximum number of elements to extract.


% Take the first 5 elements of a list
1> L = [1,2,3,4,5,6,7,8,9,10].
[1,2,3,4,5,6,7,8,9,10]
2> lists:sublist(L,5).
[1,2,3,4,5]

% Take 5 elements from a list, starting from the third position.
3> lists:sublist(L,3,5).
[3,4,5,6,7]

Please note that all functions assume the position numbering starts at 1.