Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir - how to get all elements except last in the list?

Tags:

Let say I have a list [1, 2, 3, 4]

How can I get all elements from this list except last? So, I'll have [1, 2, 3]

like image 524
asiniy Avatar asked Mar 26 '16 08:03

asiniy


People also ask

How do you access elements from a list in Elixir?

You can either do [head | tail]. = list (If you need the first element, head, as well) or tail = tl(list) (if you don't need the head) to get the tail of a list, then just map over that.

How do I get the last element in a list in Elixir?

The last() function of the List module returns the last item in the list or nil. int length = sizeof(items) / sizeof(items[0]); int x = items[length - 1];

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.

Is Elixir a list?

Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.


1 Answers

Use Enum.drop/2 like this:

list = [1, 2, 3, 4] Enum.drop list, -1      # [1, 2, 3] 
like image 59
Schpaencoder Avatar answered Sep 22 '22 05:09

Schpaencoder