Erlang Central

Extracting a Sublist

Revision as of 02:29, 31 August 2006 by Cyberlync (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Given a list, extract a segment specified by a start and an end index (inclusive).


Use the lists module sublist/2 or sublist/3 functions. The sublist/2 function takes the first N elements from a list, while the sublist/3 function takes a starting and ending point in the list.

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

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

A call to either sublist will a return a newly allocated list holding the elements of the given segment. Please note that all list functions are indexed by 1.

Note: The sublist function corrresponds to using the slice operator in Python.